Java ReadableByteChannel Copy copy(ReadableByteChannel _in, WritableByteChannel out, long amount)

Here you can find the source of copy(ReadableByteChannel _in, WritableByteChannel out, long amount)

Description

copy

License

BSD License

Declaration

public static void copy(ReadableByteChannel _in, WritableByteChannel out, long amount) throws IOException 

Method Source Code

//package com.java2s;
/**//from   w  w  w.j  a  v a 2s.  c  o  m
 * This class is part of JCodec ( www.jcodec.org ) This software is distributed
 * under FreeBSD License
 * 
 * @author The JCodec project
 * 
 */

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    public static void copy(ReadableByteChannel _in, WritableByteChannel out, long amount) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(0x10000);
        int read;
        do {
            buf.position(0);
            buf.limit((int) Math.min(amount, buf.capacity()));
            read = _in.read(buf);
            if (read != -1) {
                buf.flip();
                out.write(buf);
                amount -= read;
            }
        } while (read != -1 && amount > 0);
    }

    public static final ByteBuffer read(ByteBuffer buffer, int count) {
        ByteBuffer slice = buffer.duplicate();
        int limit = buffer.position() + count;
        slice.limit(limit);
        buffer.position(limit);
        return slice;
    }

    public static void write(ByteBuffer to, ByteBuffer from) {
        if (from.hasArray()) {
            to.put(from.array(), from.arrayOffset() + from.position(), Math.min(to.remaining(), from.remaining()));
        } else {
            to.put(toArrayL(from, to.remaining()));
        }
    }

    public static ByteBuffer duplicate(ByteBuffer bb) {
        ByteBuffer out = ByteBuffer.allocate(bb.remaining());
        out.put(bb.duplicate());
        out.flip();
        return out;
    }

    public static byte[] toArrayL(ByteBuffer buffer, int count) {
        byte[] result = new byte[Math.min(buffer.remaining(), count)];
        buffer.duplicate().get(result);
        return result;
    }
}

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)