Friday, April 25, 2014

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


1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete