Returns the subset of a byte buffer, using the given offset and length. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

Returns the subset of a byte buffer, using the given offset and length.

Demo Code


//package com.java2s;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    public static final ByteBuffer EMPTY = ByteBuffer.allocate(0);

    /**// w w w  . ja  va  2 s  . c  o  m
     * Returns the subset of a byte buffer, using the given offset and length.
     * The position and limit of the original buffer won't change after this
     * operation.
     * 
     * @param bb
     * @param offset
     * @param length
     * @return 
     */
    public static ByteBuffer getSlice(ByteBuffer bb, int offset, int length) {
        if (length == 0) {
            // very funny
            return EMPTY;
        }

        ByteOrder order = bb.order();

        // create duplicate so the position/limit of the original won't change
        bb = bb.duplicate();

        // go to offset
        bb.position(offset);

        // set new limit if length is provided, use current limit otherwise
        if (length > 0) {
            bb.limit(offset + length);
        }

        // do the actual slicing
        ByteBuffer bbSlice = bb.slice();

        // set same byte order
        bbSlice.order(order);

        return bbSlice;
    }

    /**
     * Returns the subset of a byte buffer, starting from the given offset up to
     * the current limit.
     * The position and limit of the original buffer won't change after this
     * operation.
     * 
     * @param bb
     * @param offset
     * @return 
     */
    public static ByteBuffer getSlice(ByteBuffer bb, int offset) {
        return getSlice(bb, offset, -1);
    }
}

Related Tutorials