Java ByteBuffer to String

vikky.rk picture vikky.rk · Jun 28, 2013 · Viewed 201.4k times · Source

Is this a correct approach to convert ByteBuffer to String in this way,

String k = "abcd";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new String(b.array());

if(k.equals(v))
    System.out.println("it worked");
else
    System.out.println("did not work");

The reason I ask is that is this looks too simple, whereas other approaches like Java: Converting String to and from ByteBuffer and associated problems looks more complex.

Answer

xinyong Cheng picture xinyong Cheng · Oct 4, 2016

There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();