Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ByteBuffer to byte array java [duplicate]

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.

like image 992
Powisss Avatar asked Feb 26 '15 13:02

Powisss


People also ask

What is the difference between ByteBuffer and byte array?

There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files.

What is the use of ByteBuffer in Java?

ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.


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); 
like image 152
nomis Avatar answered Oct 16 '22 05:10

nomis


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.

like image 33
Stephen C Avatar answered Oct 16 '22 06:10

Stephen C