Java I/O How to - Use UTF-16LE/UTF-16BE to Encode and Decode








Question

We would like to know how to use UTF-16LE/UTF-16BE to Encode and Decode.

Answer

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
//from   w w  w  . j  a  va 2  s  .  c om
public class MainClass {

  public static void print(ByteBuffer bb) {
    while (bb.hasRemaining())
      System.out.print(bb.get() + " ");
    System.out.println();
    bb.rewind();
  }

  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte) 'a' });
    System.out.println("Initial Byte Buffer");
    print(bb);
    Charset csets = Charset.forName("UTF-16LE");

    System.out.println(csets.name() + ":");
    print(csets.encode(bb.asCharBuffer()));
    csets.decode(bb);
    bb.rewind();

  }
}

The code above generates the following result.

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
//from   www . j  a v  a2  s  .c om
public class MainClass {

  public static void print(ByteBuffer bb) {
    while (bb.hasRemaining())
      System.out.print(bb.get() + " ");
    System.out.println();
    bb.rewind();
  }

  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte) 'a' });
    System.out.println("Initial Byte Buffer");
    print(bb);
    Charset csets = Charset.forName("UTF-16BE");

    System.out.println(csets.name() + ":");
    print(csets.encode(bb.asCharBuffer()));
    csets.decode(bb);
    bb.rewind();

  }
}

The code above generates the following result.