Java : 使用通道高效复制文件

Java : copy files efficiently with channel

我读了一篇关于传输复制的文章 在 https://www.ibm.com/developerworks/library/j-zerocopy/。建议用户通道进行IO操作。

复制文件操作的基准点在 https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html

根据基准我可以使用 nio buffernio trasfer

我还阅读了 FileChannel 在 OS 级别进行缓冲 这里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 稍微快一些。