Java ByteBuffer from Byte Array readBytes(ByteBuffer buffer, int position, int length)

Here you can find the source of readBytes(ByteBuffer buffer, int position, int length)

Description

read Bytes

License

Open Source License

Declaration

public static byte[] readBytes(ByteBuffer buffer, int position, int length) 

Method Source Code

//package com.java2s;
/**/*from   w  ww.ja  va2s .  c  o  m*/
 *  Copyright (c) 2012, 2014 Sme.UP and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 * 
 * Contributors: 
 *   Mattia Rocchi - Initial API and implementation 
 */

import java.nio.ByteBuffer;

public class Main {
    public static byte[] readBytes(ByteBuffer buffer, int position, int length) {
        assert buffer != null;

        prepare(buffer, position, length);

        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);

        return bytes;
    }

    public static void prepare(ByteBuffer buffer, int position, int length) {
        assert buffer != null;

        if (position > 0) {
            // overflow
            if (position + length > buffer.capacity())
                buffer.limit(buffer.capacity());
            else
                buffer.limit(position + length);

            buffer.position(position);
        } else {
            buffer.position(0);
            if (length > buffer.capacity())
                buffer.limit(buffer.capacity());
            else
                buffer.limit(length);
        }
    }
}

Related

  1. readBytes(ByteBuffer bb, int length)
  2. readBytes(ByteBuffer bb, int length)
  3. readBytes(ByteBuffer buf, int length)
  4. readBytes(ByteBuffer buffer)
  5. readBytes(ByteBuffer buffer, int length)
  6. readBytes(final ByteBuffer bb, final int length)
  7. toByteBuffer(byte[] array)
  8. toByteBuffer(byte[] bytes)
  9. toByteBuffer(byte[] data)