Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gets byte array from a ByteBuffer in java

Is this the recommended way to get the bytes from the ByteBuffer

ByteBuffer bb =..  byte[] b = new byte[bb.remaining()] bb.get(b, 0, b.length); 
like image 880
kal Avatar asked Mar 24 '09 21:03

kal


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.


1 Answers

Depends what you want to do.

If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:

ByteBuffer bb =..  byte[] b = new byte[bb.remaining()]; bb.get(b); 

which is equivalent as per the ByteBuffer javadocs.

like image 101
Jason S Avatar answered Nov 15 '22 18:11

Jason S