我读了一篇关于转移副本的文章 在https://www.ibm.com/developerworks/library/j-zerocopy/ .建议用户 channel 进行IO操作。
复制文件操作的基准在 https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html
根据基准测试,我可以使用 nio buffer 或 nio trasfer
我还阅读了FileChannel does buffereing in the OS level 这里How to implement a buffered / batched FileChannel in Java?
使用缓冲区或不使用缓冲区复制文件的效率更高。
nio 缓冲区代码
public static void nioBufferCopy(File sourceFile, File targetFile, int BUFFER) {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(sourceFile).getChannel();
outputChannel = new FileOutputStream(targetFile).getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER);
while (inputChannel.read(buffer) != -1) {
buffer.flip();
while(buffer.hasRemaining()){
outputChannel.write(buffer);
}
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//close resource
}
}
nio 传输代码
public void copyFileWithChannels(File aSourceFile, File aTargetFile) {
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(aSourceFile);
inChannel = inStream.getChannel();
outStream = new FileOutputStream(aTargetFile);
outChannel = outStream.getChannel();
long bytesTransferred = 0;
while(bytesTransferred < inChannel.size()){
bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size(), outChannel);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
//close resource
}
}
最佳答案
这个问题之前有人问过:
Java NIO FileChannel versus FileOutputstream performance / usefulness
TL.DR.:运行 JVM 很重要,但主要是 java.nio
稍微快一些。
关于Java : copy files efficiently with channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150483/