public class StreamCopy { public static void main(String... args) throws IOException { // copyStreamWithChannel(System.in, System.out); FileInputStream fin = new FileInputStream("data/data.txt"); copyStreamWithChannel(fin, System.out); fin.close(); } public static void copyStreamWithChannel(InputStream in, OutputStream out) throws IOException { ReadableByteChannel inChannel = Channels.newChannel(in); WritableByteChannel outChannel = Channels.newChannel(out); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); while (inChannel.read(buffer) != -1) { // prepare buffer for draining data buffer.flip(); // fill data into out channel outChannel.write(buffer); // prepare for next read operation buffer.compact(); } // flip before draining data buffer.flip(); while (buffer.hasRemaining()) { outChannel.write(buffer); } inChannel.close(); outChannel.close(); } }