copy content of src to dest, using ByteBuffer#clear() to maker user byteBuffer was fully drained, while this may cause more SYSTEM CALLS - Java java.nio

Java examples for java.nio:ByteBuffer Copy

Description

copy content of src to dest, using ByteBuffer#clear() to maker user byteBuffer was fully drained, while this may cause more SYSTEM CALLS

Demo Code


//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   w w  w.  j av a2 s  . c o  m*/
     * copy content of src to dest, <br/>
     * using {@link ByteBuffer#clear()} to maker user byteBuffer was fully
     * drained, while this may cause more SYSTEM CALLS
     * 
     * @param src
     * @param dest
     * @throws IOException
     */
    public static void channelCopy2(ReadableByteChannel src,
            WritableByteChannel dest) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(16 * 1024);// 16KB

        while (src.read(byteBuffer) != -1) {
            byteBuffer.flip();

            while (byteBuffer.hasRemaining()) {
                dest.write(byteBuffer);
            }

            // make sure byteBuffer is empty, and ready for filling
            byteBuffer.clear();
        }
    }
}

Related Tutorials