Jason S
Jason S

Reputation: 189626

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

Upvotes: 1

Views: 1169

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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

Upvotes: 5

Related Questions