Java ReadableByteChannel Read copyChannels(ReadableByteChannel input, WritableByteChannel output, int bufferSize)

Here you can find the source of copyChannels(ReadableByteChannel input, WritableByteChannel output, int bufferSize)

Description

copy Channels

License

Apache License

Declaration

public static long copyChannels(ReadableByteChannel input, WritableByteChannel output, int bufferSize)
            throws IOException 

Method Source Code

//package com.java2s;
/*/*from www  . ja v  a2  s.co m*/
 *    Copyright 2017 Frederic Thevenet
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the 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_COPY_BUFFER_SIZE = 32 * 1024;

    public static long copyChannels(ReadableByteChannel input, WritableByteChannel output) throws IOException {
        return copyChannels(input, output, DEFAULT_COPY_BUFFER_SIZE);
    }

    public static long copyChannels(ReadableByteChannel input, WritableByteChannel output, int bufferSize)
            throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
        long count = 0;
        while (input.read(buffer) != -1) {
            buffer.flip();
            count += output.write(buffer);
            buffer.compact();
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            count += output.write(buffer);
        }
        return count;
    }
}

Related

  1. copyChannels(ReadableByteChannel in, WritableByteChannel out)
  2. fill(ReadableByteChannel in, ByteBuffer buffer)
  3. getNextVIntAsLong(ByteBuffer buffer, ReadableByteChannel readChannel)
  4. infiniteReadableByteChannelFor(ByteBuffer... buffers)
  5. read(ReadableByteChannel channel, ByteBuffer buffer)