Java:使用频道有效地复制文件

时间:2017-05-24 06:25:18

标签: java io nio file-copying

我读了一篇关于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
        }              
}

1 个答案:

答案 0 :(得分:3)

之前曾问过这个问题:

  

Java NIO FileChannel versus FileOutputstream performance / usefulness

TL.DR。:您的JVM运行起来很重要,但大多数java.nio稍快一些。