Java I/O How to - Use ISO-8859-1/US-ASCII/UTF-8 Encode Decode








Question

We would like to know how to use ISO-8859-1/US-ASCII/UTF-8 Encode Decode.

Answer

//  w w  w  .jav  a 2  s.  c om
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {

  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("ISO-8859-1");

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

  }
}

The code above generates the following result.

US-ASCII

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/*from  ww  w.  jav  a 2s .  c  o  m*/
public class Main {

  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("US-ASCII");

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

  }
}

The code above generates the following result.

The following code shows how to use UTF-8 Encode Decode.

//from  w  ww  .j av  a 2 s  . co  m
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {

  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-8");

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

  }
}

The code above generates the following result.