You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中向未创建目录复制文件失败问题求助

解决Kotlin文件复制到未创建目录的问题

先梳理你代码里的几个关键问题:

  • 目录创建失败:mkdir()只能创建单级目录,如果父目录不存在会直接失败,改用mkdirs()可以递归创建所有不存在的父目录。
  • 复制目标路径错误:copyTo()的参数是目标文件的完整路径,你只传了目录路径,Kotlin会认为你要把文件复制成同名目录,导致失败,必须指定目标文件的完整路径(目录+原文件名)。
  • 重复IO操作:多次调用indexFile.readLines()会重复读取文件,应该提前把内容缓存到变量里。
  • 空指针风险:listFiles()可能返回null,直接调用first()会触发空指针异常,需要做非空处理。

修正后的代码:

import java.io.File

fun createCommitDirectory(
    parentFile: File,
    directoryIdHashName: String,
    indexFile: File,
    rootFile: File
) {
    // 递归创建目录(包含所有不存在的父目录)
    val targetDir = File(parentFile, directoryIdHashName)
    if (!targetDir.exists()) {
        targetDir.mkdirs()
    }

    // 提前读取index文件内容,避免重复IO操作
    val indexLines = indexFile.readLines()
    if (indexLines.size < 3) {
        throw IllegalArgumentException("Index file content is incomplete")
    }

    val rootParentDir = rootFile.canonicalFile.parentFile ?: run {
        throw IllegalStateException("Root file's parent directory does not exist")
    }

    // 安全获取第一个目标文件
    val firstFileName = indexLines[0]
    val firstFile = rootParentDir.listFiles()?.firstOrNull { it.name == firstFileName } ?: run {
        throw FileNotFoundException("File $firstFileName not found")
    }

    // 安全获取第二个目标文件
    val secondFileName = indexLines[2]
    val secondFile = rootParentDir.listFiles()?.firstOrNull { it.name == secondFileName } ?: run {
        throw FileNotFoundException("File $secondFileName not found")
    }

    // 指定完整的目标文件路径,完成复制
    firstFile.copyTo(File(targetDir, firstFile.name), overwrite = true)
    secondFile.copyTo(File(targetDir, secondFile.name), overwrite = true)
}

关键修改说明:

  • 用File(parentFile, directoryIdHashName)替代字符串拼接,避免跨平台路径分隔符问题。
  • mkdirs()确保所有层级的父目录都被创建,不会因为父目录不存在导致目录创建失败。
  • 缓存indexLines减少重复读取文件的IO开销。
  • 用firstOrNull()结合非空处理,避免空指针和无匹配文件时的崩溃。
  • copyTo()的目标参数明确指定为「目标目录+原文件名」,确保文件被正确复制到目标目录下;overwrite = true可根据需求调整,用于覆盖同名文件。

另外,copyRecursive()是用于复制整个目录的方法,你复制的是单个文件,所以用copyTo()就足够,不需要用copyRecursive()。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:43:30