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

Java实现源目录全量文件复制到目标目录的方法报错求助

代码问题排查与修复

现有代码的核心问题

  • 文件复制目标路径错误:调用Files.copy(p, rDest)时直接传入目标目录,会触发FileAlreadyExistsException,正确做法是将目标路径拼接为rDest下与源文件同名的路径,即rDest.resolve(p.getFileName())
  • 异常被静默吞噬:所有IOException的catch块都是空实现,运行出错时没有任何错误提示,完全无法定位问题
  • 校验异常无有效信息:参数校验不通过时直接抛出无信息的RuntimeException,无法区分是源目录不存在、源不是目录,还是目标目录已存在三种错误场景
  • 不支持递归复制子目录:现有逻辑只能复制源目录下的一级文件,遇到子目录会仅复制空目录,不会同步目录内的内容
  • 冗余判断逻辑:Files.createDirectory(rDest)执行成功后不需要再判断Files.exists(rDest),创建失败会直接抛出异常进入catch块,冗余判断无实际意义

修复后代码

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public void copyTo(Path rSource, Path rDest) {
    // 前置参数校验
    if (!Files.exists(rSource) || !Files.isDirectory(rSource)) {
        throw new RuntimeException("源路径不存在或不是目录");
    }
    if (Files.exists(rDest)) {
        throw new RuntimeException("目标路径已存在");
    }

    try {
        // 创建目标根目录
        Files.createDirectory(rDest);
        // 遍历源目录下所有内容
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
            for (Path sourceItem : stream) {
                Path targetItem = rDest.resolve(sourceItem.getFileName());
                if (Files.isDirectory(sourceItem)) {
                    // 递归复制子目录
                    copyTo(sourceItem, targetItem);
                } else {
                    // 复制文件,COPY_ATTRIBUTES参数用于保留源文件的修改时间、权限等属性
                    Files.copy(sourceItem, targetItem, StandardCopyOption.COPY_ATTRIBUTES);
                }
            }
        }
    } catch (IOException e) {
        // 包装异常抛出,避免静默失败
        throw new RuntimeException("目录复制失败: " + e.getMessage(), e);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:18:05