How to convert ByteBuffer to String

April 23, 2020 | No comments

Convert ByteBuffer to String and viceversa

ByteBuffer Class is part of Java NIO. It extends java.nio.Buffer and used to handle data read and write to NIO Channels. This article demonstrates few ways to handle conversion between ByteBuffer to String and converting String to ByteBuffer object.
Convert String to ByteBuffer
Following code converts the String data to ByteBuffer object using Charset.forName. We need to specify the appropriate character set .
String data = "this is my string";
ByteBuffer buff = Charset.forName("UTF-8").encode(data);
Convert ByteBuffer to String
Following code sample shows two methods, both can be used to convert ByteBuffer object back to a String. We need to specify the same character set, that was used to encode, otherwise we might get a different String.
public static String getData (ByteBuffer buff) {
    return new String(buff.array(), StandardCharsets.UTF_8 );
public static String getData2 (ByteBuffer buff) {
    return StandardCharsets.UTF_8.decode(buff).toString();

No comments :

Post a Comment

Please leave your message queries or suggetions.