我正在尝试在批处理期间使用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上提出的代码,但自从我升级到Java7后,我想要改变它。
发布于 2017-06-30 19:35:16
也许你可以尝试使用不同的库?
例如,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);
}或者仅仅使用FileStream?
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();
}https://stackoverflow.com/questions/44844546
复制相似问题