Java: Retreive ByteArray from Direct ByteBuffer and convert it to String

I assume you understand what is Direct ByteBuffer. I was trying to retrieve byte[] from Direct ByteBuffer

ByteBuffer buffer = ByteBuffer.allocateDirect(10000);
.....
.....
buffer.flip();
byte[] data = buffer.array();

and I was getting this error

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.nio.ByteBuffer.array(ByteBuffer.java:959)

I was able to solve this as follows

ByteBuffer buffer = ByteBuffer.allocateDirect(10000);
.....
.....
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
// Here you hava data populated inside data[] array
String token = new String(data);

See also