Search code examples
javastringniobytebuffer

Converting part of a ByteBuffer to a String


I have a ByteBuffer containing bytes that were derived by String.getBytes(charsetName), where "containing" means that the string comprises the entire sequence of bytes between the ByteBuffer's position() and limit().

What's the best way for me to get the string back? (assuming I know the encoding charset) Is there anything better than the following (which seems a little clunky)

byte[] ba = new byte[bbuf.remaining()];
bbuf.get(ba);
try {
    String s = new String(ba, charsetName);
}
catch (UnsupportedEncodingException e) {
    /* take appropriate action */
}

Solution

  • String s = Charset.forName(charsetName).decode(bbuf).toString();