Wednesday, June 18, 2008

ByteBuffer to String

ByteBuffer bytebuff = ...;
byte[] bytearr = new byte[bytebuff.remaining()];
bytebuff.get(bytearray);
String s = new String(bytearray);

9 comments:

harrier6 said...

On the money! Thanks for the post.

Anonymous said...
This comment has been removed by the author.
Anonymous said...

So a very simple and excelent post. Just saying that you have missed in naming the first byte[], first its name is bytearr, and later it's named as bytearray.

Thank you

Unknown said...

This is bad advice, never use new String(byte[]), it uses the platform default encoding and leads to fragile code that doesn't work on all platforms.

Marko Mitic said...

Thanks, it's useful.

Chris Dennett said...

This is also bad because it doesn't take into account the current position, the remaining amount comes after the position...

ma3at said...

Thanks. Very nice tip, and to refer to Chris Dennett remark, u can use instead: public String(byte[] bytes, int offset, int length, Charset charset)

Cheers

Satya said...

Waaw.. thats wat I was looking for.. Thanks a lot! :)

Satya said...

Waaw.. thats wat I was looking for.. Thanks a lot! :)