Skip to content

Instantly share code, notes, and snippets.

@qingniufly
Created March 28, 2017 07:31
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop.
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop.
Java NIO, ByteBuffer <--> String
// ByteBuffer to String
String s = Charset.forName("UTF-8").decode(byteBuffer).toString();
// String to ByteBuffer
ByteBuffer buff = Charset.forName("UTF-9").encode("Hello, World!");
// String to ByteBuffer
public static ByteBuffer str_to_bb(String msg, Charset charset){
return ByteBuffer.wrap(msg.getBytes(charset));
}
// ByteBuffer to String
public static String bb_to_str(ByteBuffer buff, Charset charset){
byte[] bytes;
if (buff.hasArray()) {
bytes = buff.array();
} else {
bytes = new byte[buff.remaining()];
buff.get(bytes);
}
return new String(bytes);
}
@artob
Copy link

artob commented Aug 10, 2018

UTF-9?

@mehmetminanc
Copy link

Hmmmmmmm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment