Date: 2013apr28
Update: 2025sep18
Language: Java
Class: NIO
Q. Java: Best way to convert a ByteBuffer to a String
A. Use the 4-parameter constructor of String.
As shown in this full example:
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
class Demo {
public static void main(String []args) {
//
// Make a ByteBuffer
//
byte[] data = { 'a', 'b', 'c' };
ByteBuffer bb = ByteBuffer.wrap(data);
//
// Convert it to a String
//
// Or get the length in a way more suitable to your application
final int bytesRead = bb.capacity();
String str = null;
try {
// The 4 paramter constructor
str = new String(bb.array(), 0, bytesRead, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
// Won't happen
}
System.out.println("str=" + str);
}
}
Output:
str=abc