copy content of src to dest, using ByteBuffer#compact() when inner ByteBuffer was not fully drained - Java java.nio

Java examples for java.nio:ByteBuffer Copy

Description

copy content of src to dest, using ByteBuffer#compact() when inner ByteBuffer was not fully drained

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   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);
        }
    }
}

Related Tutorials