Convert ByteBuffer to byte array java

Powisss picture Powisss · Feb 26, 2015 · Viewed 68.8k times · Source

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.

Answer

nomis picture nomis · Feb 26, 2015

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);