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

use*_*949 18 java

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

luk*_*ymo 49

选择你喜欢的:

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

FileUtils示例:

File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Yab*_*aba 20

Apache Commons IO可以为您提供帮助.看看FileUtils.