如何将文件夹及其所有子文件夹和文件复制到另一个文件夹?
答案 0 :(得分:49)
选择您喜欢的内容:
FileUtils示例:
File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);
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);
}
}
}
答案 1 :(得分:20)
Apache Commons IO可以帮到你。看看FileUtils。
答案 2 :(得分:2)
查看java.io.File中的一堆函数。
您将遍历现有结构和mkdir,保存等以实现深层复制。
答案 3 :(得分:0)
JAVA NIO将帮助您解决问题。请看看这个 http://tutorials.jenkov.com/java-nio/files.html#overwriting-existing-files