How to copy from ByteBuffer to String

1. Simple but not exactly right    

simply create string with byte array from ByteBuffer 

ByteBuffer buffer = ByteBuffer.allocate(1024);

buffer.put(“aabcde”.getBytes());


String s =
new String(buffer.array(), "");
 //or
String s = new String(buffer.array(), "UTF-8");

System.out.println(s);


2. More elegance way

buffer.put(“aabcde”.getBytes());
byte[] bytes = new byte[buffer.position()];
buffer.flip();       
buffer.get(bytes);
String s = new String(bytes); // or new String(bytes, "UTF-8");
System.out.println(s);

Leave a Reply

Your email address will not be published. Required fields are marked *