Transfers as much data as possible to and from ByteBuffer. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

Transfers as much data as possible to and from ByteBuffer.

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**/*from   w w w  . j a v  a2  s. c o m*/
     * Transfers as much data as possible from from to to.
     * Returns how much data was transferred.
     * 
     * @param from
     * @param to
     * @return
     */
    public static int transfer(ByteBuffer from, ByteBuffer to) {
        if (from == null)
            return 0;

        int read = 0;

        if (from.position() > 0) {
            from.flip();
            int remaining = from.remaining();
            int toRemaining = to.remaining();
            if (toRemaining >= remaining) {
                to.put(from);
                read += remaining;
            } else {
                int limit = from.limit();
                int position = from.position();
                from.limit(position + toRemaining);
                to.put(from);
                read += toRemaining;
                from.limit(limit);
            }
            from.compact();
        }

        return read;
    }

    public static int transfer(ByteBuffer from, ByteBuffer to,
            boolean needsFlip) {
        if (needsFlip)
            return transfer(from, to);
        else {

            if (from == null)
                return 0;

            int read = 0;
            if (from.hasRemaining()) {
                int remaining = from.remaining();
                int toRemaining = to.remaining();
                if (toRemaining >= remaining) {
                    to.put(from);
                    read += remaining;
                } else {
                    int limit = from.limit();
                    int position = from.position();
                    from.limit(position + toRemaining);
                    to.put(from);
                    read += toRemaining;
                    from.limit(limit);
                }
            }
            return read;
        }
    }

    public static long transfer(ByteBuffer from, ByteBuffer[] to,
            int offset, int length) {
        long read = 0;
        for (int i = offset; i < offset + length; i++)
            read += transfer(from, to[i]);

        return read;
    }
}

Related Tutorials