views:

1339

answers:

3

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);
+1  A: 

bb.array() will return the byte array that backs the buffer.

Mark
...if there is one. "Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array."
Michael Myers
Jason S
+2  A: 

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.

Jason S
+1  A: 

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

Peter Lawrey