Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
java convert bytebuffer to string
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
Method Usage
ByteBuffer bf = string2ByteBuffer("test", Charset.forName("UTF-8"));
public static ByteBuffer string2ByteBuffer(String s, Charset charset) {
return ByteBuffer.wrap(s.getBytes(charset));
public static String byteBuffer2String(ByteBuffer buf, Charset charset) {
byte[] bytes;
if (buf.hasArray()) {
bytes = buf.array();
} else {
bytes = new byte[buf.remaining()];
return new String(bytes, charset);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment