Java ByteBuffer to Byte Array getBytesAtOffset(ByteBuffer buffer, int offset, int length)

Here you can find the source of getBytesAtOffset(ByteBuffer buffer, int offset, int length)

Description

Given a java.nio.ByteBuffer get bytes in an absolute offset without altering its current position.

License

Open Source License

Parameter

Parameter Description
buffer The java.nio.ByteBuffer to read data from.
offset The absolute offset from which starting to extract data.
length How many bytes to extract.

Return

The exctracted bytes as a byte array.

Declaration

public static byte[] getBytesAtOffset(ByteBuffer buffer, int offset, int length) 

Method Source Code


//package com.java2s;
/*//from   ww  w .j ava 2 s. c o m
 * Copyright (c) Fabio Falcinelli 2016.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Given a {@link java.nio.ByteBuffer} get bytes in an absolute offset without altering its current position.
     * <p>
     * The operation is {@code synchronized} over the {@code buffer} to avoid thread interference.
     *
     * @param buffer The {@link java.nio.ByteBuffer} to read data from.
     * @param offset The absolute offset from which starting to extract data.
     * @param length How many bytes to extract.
     * @return The exctracted bytes as a byte array.
     */
    public static byte[] getBytesAtOffset(ByteBuffer buffer, int offset, int length) {
        byte[] data = new byte[length];
        synchronized (buffer) {
            int position = buffer.position();
            buffer.position(offset);
            buffer.get(data);
            buffer.position(position);
        }
        return data;
    }
}

Related

  1. getBytes(ByteBuffer byteBuffer, int length)
  2. getBytes(ByteBuffer bytes)
  3. getBytes(ByteBuffer floatCalculator, float number)
  4. getBytes(ByteBuffer in)
  5. getBytes(MappedByteBuffer buffer, int pos, byte[] target)
  6. getBytesFromBuffer(ByteBuffer buffer, int len)
  7. getBytesFromByteBuffer(ByteBuffer byteBuffer)
  8. getBytesFromByteBuffer(Object obj)
  9. readBytes(byte[] dest, int offset, int length, ByteBuffer buffer)