我读了一篇关于trasfer copy的文章 在https://www.ibm.com/developerworks/library/j-zerocopy/。这建议用户通道进行IO操作。
有一个复制文件操作的banchmark可用于 https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html
根据基准,我可以使用 nio buffer 或 nio trasfer
我还阅读了 FileChannel在操作系统级别进行修复 这里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 trasfer的代码
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
}
}
答案 0 :(得分:3)
之前曾问过这个问题:
Java NIO FileChannel versus FileOutputstream performance / usefulness
TL.DR。:您的JVM运行起来很重要,但大多数java.nio
稍快一些。