Converting Byte Arrays to and from Strings using Charset - Java Internationalization

Java examples for Internationalization:Charset

Description

Converting Byte Arrays to and from Strings using Charset

Demo Code

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.SortedMap;

public class Main {

  public static void main(String[] args) {
    byte[] legacySJIS = { 65,66,67};

    // Convert a byte[] to a String
    Charset cs = Charset.forName("SJIS");
    String greeting = new String(legacySJIS, cs);
    System.out.printf("Greeting: %s\n", greeting);

    // Convert a String to a byte[]
    byte[] toSJIS = greeting.getBytes(cs);

    // Confirm that the original array and newly converted array are same
    Boolean same = false;/*from  w  ww .  j a  v a2  s.  c  om*/
    if (legacySJIS.length == toSJIS.length) {
      for (int x = 0; x < legacySJIS.length; x++) {
        if (legacySJIS[x] != toSJIS[x])
          break;
      }
      same = true;
    }
    System.out.printf("Same: %s\n", same.toString());

    SortedMap<String, Charset> charsets = Charset.availableCharsets();
    Iterator<Charset> cc = charsets.values().iterator();
    int size = charsets.size();
    while (cc.hasNext()) {
      System.out.printf("Charset: %s\n", cc.next().displayName());
    }
    System.out.printf("Count: %d\n", size);
  }

}

Related Tutorials