1

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 */
}

1 Answer 1

5
String s = Charset.forName(charsetName).decode(bbuf).toString();
Sign up to request clarification or add additional context in comments.

1 Comment

whee! Great -- it "smelled" like there should be something to do this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.