Java递归文件复制优化
我有一个小应用程序,可以将PDF文件(子文件夹)复制到目标文件夹。但它的工作非常慢,我想优化它。你能帮我吗
代码:
public void pdfFolderCopy(File src, File dest)
throws IOException {
if (src.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
}
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
pdfFolderCopy(srcFile, destFile);
}
} else {
if (!dest.exists()) {
System.out.println("Copying: " + src);
//Use the Apache IO copyFile method:
FileUtils.copyFile(src, dest);
}
}
}
如果每个文件都已经存在,它将运行大约一分钟半。大约5分钟,如果我们需要复制大约500个文件
# 1 楼答案
代码中唯一真正耗时的任务是
FileUtils.copyFile()
。必要的时间将根据要复制的文件数量及其大小而增加关于您的代码,我建议您提取
dest
目录的检查,因为它不应该在复制过程中更改。在开始pdfFolderCopy
之前,检查并创建dest
目录