有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    代码中唯一真正耗时的任务是FileUtils.copyFile()。必要的时间将根据要复制的文件数量及其大小而增加

    关于您的代码,我建议您提取dest目录的检查,因为它不应该在复制过程中更改。在开始pdfFolderCopy之前,检查并创建dest目录