Java CharBuffer encode to ByteBuffer
import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; public class Main { public static void main(String[] args) { try {/* w w w .ja va 2 s .co m*/ String unicodeString = "\u0012\u0023\u1023"; System.out.printf("Original string: %s\n", unicodeString); CharBuffer srcBuffer = CharBuffer.wrap(unicodeString); ByteBuffer targetBytes = encodeBuffer("UTF8", srcBuffer); printBytes(targetBytes); CharBuffer roundtripBuffer = decodeBuffer("UTF8", targetBytes); printCharBuffer(roundtripBuffer); } catch (CharacterCodingException ex) { ex.printStackTrace(); } } public static ByteBuffer encodeBuffer(String charsetName, CharBuffer charBuffer) throws CharacterCodingException { Charset charset = Charset.forName(charsetName); CharsetEncoder encoder = charset.newEncoder(); ByteBuffer targetBuffer = encoder.encode(charBuffer); return targetBuffer; } public static CharBuffer decodeBuffer(String charsetName, ByteBuffer srcBuffer) throws CharacterCodingException { Charset charset = Charset.forName(charsetName); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(srcBuffer); return charBuffer; } private static void printCharBuffer(CharBuffer buff) { String str = buff.toString(); System.out.printf("Roundtrip string: %s\n", str); } private static void printBytes(ByteBuffer bytes) { System.out.print("Bytes: "); byte[] byteArray = bytes.array(); for (byte b : byteArray) { if (b == 0) break; System.out.printf("%2x ", b); } System.out.printf("\n"); } }