Gets byte array from a ByteBuffer in java Gets byte array from a ByteBuffer in java arrays arrays

Gets byte array from a ByteBuffer in java


Depends what you want to do.

If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:

ByteBuffer bb =..byte[] b = new byte[bb.remaining()];bb.get(b);

which is equivalent as per the ByteBuffer javadocs.


Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");ByteBuffer b1 = ByteBuffer.wrap(test);byte[] hello = new byte[6];b1.get(hello); // "Hello "ByteBuffer b2 = b1.slice(); // position = 0, string = "World"byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".byte[] world = new byte[5];b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.


As simple as that

  private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {    byte[] bytesArray = new byte[byteBuffer.remaining()];    byteBuffer.get(bytesArray, 0, bytesArray.length);    return bytesArray;}