Files.copy在速度上变化很大



我正在尝试在批处理期间使用方法Files.copy复制文件。每次运行都需要不同的时间来复制文件。我每次都使用完全相同的 12 个文件。它从 30 秒到 30 分钟不等。 这怎么可能?

public void copyFile(File sourceFile, File targetFile, CopyOption... options) throws IOException {
    Files.copy(sourceFile.toPath(), targetFile.toPath(), options);
}

作为选项,我使用StandardCopyOption.COPY_ATTRIBUTES。

我曾经使用 http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java 提出的代码,但自从我升级到Java 7以来,我想改变它。

也许您可以尝试使用其他库?

例如Apache Commons:

       /**
        * <dependency>
        * <groupId>org.apache.commons</groupId>
        * <artifactId>commons-io</artifactId>
        *  <version>1.3.2</version>
        *  </dependency>
        **/
        private void fileCopyUsingApacheCommons() throws IOException {
            File fileToCopy = new File("/tmp/test.txt");
            File newFile = new File("/tmp/testcopied.txt");
            File anotherFile = new File("/tmp/testcopied2.txt");
            FileUtils.copyFile(fileToCopy, newFile);
        }

还是仅使用文件流?

    private void fileCopyUsingFileStreams() throws IOException {
        File fileToCopy = new File("/tmp/test.txt");
        FileInputStream input = new FileInputStream(fileToCopy);
        File newFile = new File("/tmp/test_and_once_again.txt");
        FileOutputStream output = new FileOutputStream(newFile);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }
        input.close();
        output.close();
    }

最新更新