javaioniofile-copying

Java : copy files efficiently with channel


I read one article regarding trasfer copy at https://www.ibm.com/developerworks/library/j-zerocopy/. which suggest to user channel for IO operation.

There is a banchmark of copy file operation available at https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html

As per benchmark I can use either nio buffer or nio trasfer

I also read FileChannel does buffereing in the OS level here How to implement a buffered / batched FileChannel in Java?

Which is more efficient way to copy file with buffer or with out buffer.

code for nio buffer

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
        }
}

code for 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
        }              
}

Solution

  • This question was asked before:

    Java NIO FileChannel versus FileOutputstream performance / usefulness

    TL.DR.: It matters what your JVM is running on, but mostly the java.nio is slightly faster.