Convert ByteBuffer to byte array java

JavaArraysBytebuffer

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPowisssView Question on Stackoverflow
Solution 1 - JavanomisView Answer on Stackoverflow
Solution 2 - JavaStephen CView Answer on Stackoverflow