Use java.nio.charset.CharsetEncoder and java.nio.charset.CharsetDecoder to convert Unicode character buffers to and from byte buffers - Java Internationalization

Java examples for Internationalization:Charset

Description

Use java.nio.charset.CharsetEncoder and java.nio.charset.CharsetDecoder to convert Unicode character buffers to and from byte buffers

Demo Code

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 ByteBuffer encodeBuffer(String charsetName,
      CharBuffer charBuffer) throws CharacterCodingException {
    Charset charset = Charset.forName(charsetName);
    CharsetEncoder encoder = charset.newEncoder();
    ByteBuffer targetBuffer = encoder.encode(charBuffer);
    return targetBuffer;
  }//from   www  .j a v a2s  .c o  m
  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");
  }
  public static void main(String[] args) throws Exception {
    String unicodeString = "this is a test";
    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);
  }
}

Result


Related Tutorials