public static void copy ( ReadableByteChannel inChannel , WritableByteChannel outChannel ) throws IOException { if ( inChannel instanceof FileChannel ) { ( ( FileChannel ) inChannel ) . transferTo ( 0 , ( ( FileChannel ) inChannel ) . size ( ) , outChannel ) ; } else { final ByteBuffer buffer = ByteBuffer . allocateDirect ( 16 * 1024 ) ; try { while ( inChannel . read ( buffer ) != - 1 ) { // prepare the buffer to be drained buffer . flip ( ) ; // write to the channel, may block outChannel . write ( buffer ) ; // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer . compact ( ) ; } // EOF will leave buffer in fill state buffer . flip ( ) ; // make sure the buffer is fully drained. while ( buffer . hasRemaining ( ) ) { outChannel . write ( buffer ) ; } } finally { IOUtils . close ( inChannel ) ; IOUtils . close ( outChannel ) ; } } }
Copy the readable byte channel to the writable byte channel