Java ByteBuffer from Byte Array bufToArray(ByteBuffer b)

Here you can find the source of bufToArray(ByteBuffer b)

Description

Converts ByteBuffer to an array - if the buffer is backed by the array but doesn't fully overlap it it performs an array copy.

License

Open Source License

Parameter

Parameter Description
b byte buffer to be converted to an array

Return

all remaining bytes from the bytebuffer as a byte array

Declaration

public static byte[] bufToArray(ByteBuffer b) 

Method Source Code

//package com.java2s;
/**/*from w w  w.j a v  a 2s . co m*/
 * Copyright (C) 2015 Michal Harish
 * <p/>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * <p/>
 * 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 General Public License for more details.
 * <p/>
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
    /**
     * Converts ByteBuffer to an array - if the buffer is backed by the array but doesn't
     * fully overlap it it performs an array copy. If the buffer is not backed by an array
     * it constructs a new array and reads the buffer content into it.
     * @param b byte buffer to be converted to an array
     * @return all remaining bytes from the bytebuffer as a byte array
     */
    public static byte[] bufToArray(ByteBuffer b) {
        if (b.hasArray()) {
            if (b.position() == 0 && b.arrayOffset() == 0 && b.limit() == b.capacity()) {
                return b.array();
            } else {
                return Arrays.copyOfRange(b.array(), b.arrayOffset(), b.arrayOffset() + b.remaining());
            }
        } else {
            byte[] a = new byte[b.remaining()];
            int bp = b.position();
            b.get(a);
            b.position(bp);
            return a;
        }
    }
}

Related

  1. asByteBuffer(byte... arguments)
  2. buffer2Bytes(ByteBuffer bbuf)
  3. bufToArray(ByteBuffer b)
  4. byteBuffer(byte[] a)
  5. readByteArray(ByteBuffer byteBuffer, int length)
  6. readByteArray(ByteBuffer in)
  7. readByteArray(ByteBuffer logBuf)