title: Java : copy files efficiently with channel
body: <p>I read one article regarding trasfer copy 
  at <a href="https://www.ibm.com/developerworks/library/j-zerocopy/" rel="nofollow noreferrer">https://www.ibm.com/developerworks/library/j-zerocopy/</a>. which suggest to user channel for IO operation.</p>
  
  <p>There is a banchmark of copy file operation available at
  <a href="https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html" rel="nofollow noreferrer">https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html</a></p>
  
  <p>As per benchmark I can use either <strong>nio buffer</strong> or <strong>nio trasfer</strong></p>
  
  <p>I also read <strong>FileChannel does buffereing in the OS level</strong>
  here <a href="https://stackoverflow.com/questions/12587125/how-to-implement-a-buffered-batched-filechannel-in-java/12587260#12587260">How to implement a buffered / batched FileChannel in Java?</a></p>
  
  <p>Which is more efficient way to copy file with buffer or with out buffer.</p>
  
  <p><strong>code for nio buffer</strong></p>
  
  <pre><code>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></pre>
  
  <p><strong>code for nio trasfer</strong></p>
  
  <pre><code>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 &lt; inChannel.size()){
                  bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size(), outChannel);
              }
          }       
          catch (Exception e) {
              e.printStackTrace();
          }
          finally {
              //close resource
          }              
  }
  </code></pre>