我该如何将一个文件夹及其所有子文件夹和文件复制到另一个文件夹中?
选择你喜欢的方法:
使用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);
}
}
}
Apache Commons IO可以帮你搞定这个问题。请看FileUtils。
查看java.io.File获取一系列函数。
您将遍历现有结构并进行mkdir、save等操作,以实现深度复制。
copyFile
可以通过使用Files#copy
方法进行增强(因为它使用本机钩子,如果可用)。 - n247s