Java ReadableByteChannel Copy fastChannelCopy(final ReadableByteChannel input, final WritableByteChannel output, long toRead)

Here you can find the source of fastChannelCopy(final ReadableByteChannel input, final WritableByteChannel output, long toRead)

Description

fast Channel Copy

License

Open Source License

Declaration

private static void fastChannelCopy(final ReadableByteChannel input, final WritableByteChannel output,
            long toRead) 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 {
    private static final int DEFAULT_BUFFER_SIZE = 10240;

    private static void fastChannelCopy(final ReadableByteChannel input, final WritableByteChannel output,
            long toRead) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
        int read;
        while (toRead > 0) {
            read = input.read(buffer);/*from w  w  w  .  j av  a  2s  . c  o  m*/
            if (read > 0) {
                // prepare the buffer to be drained
                buffer.flip();

                if (toRead < read) {
                    buffer.limit((int) toRead);
                }

                // write to the channel, may block
                output.write(buffer);

                // If partial transfer, shift remainder down
                // If buffer is empty, same as doing clear()
                buffer.compact();
                toRead -= read;
            } else {
                break;
            }
        }
    }
}

Related

  1. copy(ReadableByteChannel input, WritableByteChannel output, long start, long length)
  2. copy(ReadableByteChannel inputChannel, WritableByteChannel outputChannel)
  3. copy(ReadableByteChannel source, WritableByteChannel destination)
  4. copy(ReadableByteChannel src, WritableByteChannel dest)
  5. copyTo(ReadableByteChannel from, WritableByteChannel to)
  6. fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
  7. fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
  8. fastChannelCopy(ReadableByteChannel src, WritableByteChannel dest)
  9. fastCopy(final ReadableByteChannel src, final WritableByteChannel dest)