Java File Read via ByteBuffer channelCopy2(ReadableByteChannel src, WritableByteChannel dest)

Here you can find the source of channelCopy2(ReadableByteChannel src, WritableByteChannel dest)

Description

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

License

Open Source License

Parameter

Parameter Description
src a parameter
dest a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void channelCopy2(ReadableByteChannel src, WritableByteChannel dest) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    /**// w ww.  j a  v a 2  s .c  om
     * 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

  1. blockingRead(SocketChannel so, long timeout, int bytes)
  2. channelCopy(@Nonnull @WillNotClose final ReadableByteChannel aSrc, @Nonnull @WillNotClose final WritableByteChannel aDest)
  3. ClientReadWithBlock(SocketChannel sc)
  4. ClientReadWithWait(SocketChannel sc)
  5. copy(final ReadableByteChannel src, final WritableByteChannel dest)
  6. copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)