Does anyone know how to convert ByteBuffer to byte[] array? I need to get byte array from my ByteBuffer. When I run bytebuffer.hasArray() it returns no. Every question I looked so far is converting byte array to byteBuffer, but I need it other way around.
Thank you.
2 Answers
ByteBuffer exposes the bulk get(byte[]) method which transfers bytes from the buffer into the array. You'll need to instantiate an array of length equal to the number of remaining bytes in the buffer.
ByteBuffer buf = ...
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
7 Comments
J Richard Snape
Code only anwers are normally improved by adding some text explaining what the code is doing - can you add a bit of text to explain to the OP?
BoygeniusDexter
don't forget to call
buf.rewind(), otherwise buf.remaining() will return with incorrect valuejpganz18
hi, buf.get(arr) still returns a ByteBuffer, is there any other alternative?
gioravered
@SeetharamaniTmr - The bytes are being filled into "arr" variable and are not the returned value.
Grigory K
byte[] arr = new byte[ buf.position() ]; buf.rewind(); buf.get(arr) |
If hasArray() reports false then, calling array() will throw an exception.
In that case, the only way to get the data in a byte[] is to allocate a byte[] and copy the bytes to the byte[] using get(byte[]) or similar.
2 Comments
user3441843
It's so lame that I cannot get the backing array without modifying the buffer position...
Stephen C
You can easily record the position, copy the bytes and then reset the position.
byteBuffer.array()?false.