Created
March 28, 2017 07:31
-
-
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop.
Java NIO, ByteBuffer <--> String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UTF-9?