如何将一个文件夹及其所有子文件夹和文件复制到另一个文件夹中。

18

我该如何将一个文件夹及其所有子文件夹和文件复制到另一个文件夹中?

4个回答

53

选择你喜欢的方法:

  • 来自Apache Commons IO的FileUtils(最简单、最安全的方式

使用FileUtils的示例:

File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);
  • 手动实现,在Java 7之前示例(更改:在finally块中关闭流)
  • 手动实现,Java >=7

使用Java 7中的AutoCloseable特性的示例:

public void copy(File sourceLocation, File targetLocation) throws IOException {
    if (sourceLocation.isDirectory()) {
        copyDirectory(sourceLocation, targetLocation);
    } else {
        copyFile(sourceLocation, targetLocation);
    }
}

private void copyDirectory(File source, File target) throws IOException {
    if (!target.exists()) {
        target.mkdir();
    }

    for (String f : source.list()) {
        copy(new File(source, f), new File(target, f));
    }
}

private void copyFile(File source, File target) throws IOException {        
    try (
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target)
    ) {
        byte[] buf = new byte[1024];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
    }
}

这个代码是可以工作的,但是如果出现异常,你就不会关闭流:你应该添加一个try catch finally块。 - Tim Autin
@Tim,没错。已修复。 - lukastymo
1
copyFile 可以通过使用 Files#copy 方法进行增强(因为它使用本机钩子,如果可用)。 - n247s
有一个错误。如果我想要复制1个文件,它不起作用——因为targetLocation应该始终是一个文件夹,而在你的代码中,它总是在copyFile中被用作文件。 - Eugene Kartoyev

21

Apache Commons IO可以帮你搞定这个问题。请看FileUtils


链接已失效,请更新。 - 4ndro1d
1
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29 - Raghunandan

2

查看java.io.File获取一系列函数。

您将遍历现有结构并进行mkdir、save等操作,以实现深度复制。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接