Java examples for java.nio:ByteBuffer Copy
copy content of src to dest, using ByteBuffer#compact() when inner ByteBuffer was not fully drained
//package com.java2s; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; public class Main { /**//from www. jav a 2s.c o m * copy content of src to dest, <br/> * using {@link ByteBuffer#compact()} when inner ByteBuffer was not fully * drained * * @param src * @param dest * @throws IOException */ public static void channelCopy1(ReadableByteChannel src, WritableByteChannel dest) throws IOException { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(16 * 1024);// 16KB while (src.read(byteBuffer) != -1) { byteBuffer.flip();// prepare to be drained dest.write(byteBuffer);// may block!!! byteBuffer.compact();// in case of byteBuffer is not fully drained } // now byteBuffer is in fill state byteBuffer.flip(); // make sure byteBuffer is fully drained while (byteBuffer.hasRemaining()) { dest.write(byteBuffer); } } }