Skip to content

Instantly share code, notes, and snippets.

@reddikih
Last active April 10, 2020 18:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reddikih/00ed63847f9f4e620e9d4772d69cbee5 to your computer and use it in GitHub Desktop.
Save reddikih/00ed63847f9f4e620e9d4772d69cbee5 to your computer and use it in GitHub Desktop.
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 {
buf.rewind();
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