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.
Asked
Active
Viewed 1.1e+01k times
60

Axel Fontaine
- 34,542
- 16
- 106
- 137

Powisss
- 1,072
- 3
- 9
- 16
-
3Have you tried `byteBuffer.array()`? – Johnny Willer Feb 26 '15 at 13:50
-
1@JohnnyWiller - it will fail ... hasArray is returning `false`. – Stephen C Feb 26 '15 at 13:55
-
Yes i did with no success. – Powisss Feb 26 '15 at 13:55
-
Ok.. I think nomis's answer will work :) – Johnny Willer Feb 26 '15 at 13:56
2 Answers
129
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);
-
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? – J Richard Snape Feb 26 '15 at 14:13
-
12don't forget to call `buf.rewind()`, otherwise `buf.remaining()` will return with incorrect value – BoygeniusDexter Jun 04 '18 at 14:00
-
hi, buf.get(arr) still returns a ByteBuffer, is there any other alternative? – jpganz18 Mar 03 '20 at 14:48
-
This is not converting the ByteBuffer to byte array. Its still returning ByteBuffer. – Seetha Mar 20 '20 at 19:55
-
4@SeetharamaniTmr - The bytes are being filled into "arr" variable and are not the returned value. – gioravered Apr 12 '20 at 08:58
-
-
1`byte[] arr = new byte[ buf.position() ]; buf.rewind(); buf.get(arr)` – Grigory K Jul 30 '21 at 11:47
9
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.

Stephen C
- 698,415
- 94
- 811
- 1,216