【发布时间】:2011-07-19 03:08:20
【问题描述】:
如何将文件夹及其所有子文件夹和文件复制到另一个文件夹中?
【问题讨论】:
标签: java
如何将文件夹及其所有子文件夹和文件复制到另一个文件夹中?
【问题讨论】:
标签: java
选择你喜欢的:
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);
}
}
}
【讨论】:
copyFile 可以通过使用 Files#copy 方法来增强(因为它使用本地挂钩,如果可用的话)。
Apache Commons IO 可以为您解决问题。看看FileUtils。
查看 java.io.File 中的一堆函数。
您将遍历现有结构和 mkdir、保存等以实现深拷贝。
【讨论】:
JAVA NIO 将帮助您解决问题。请看看这个 http://tutorials.jenkov.com/java-nio/files.html#overwriting-existing-files.
【讨论】: