Java String convert from byte array by Charset

Description

Java String convert from byte array by Charset

import java.nio.charset.Charset;
import java.util.Arrays;

public class Main {

   public static void main(String[] args) {
      byte[] legacySJIS = { (byte) 0x82, (byte) 0xB1, (byte) 0x82, (byte) 0xF1, (byte) 0x82, (byte) 0xC9, (byte) 0x82,
            (byte) 0xBF, (byte) 0x82, (byte) 0xCD, (byte) 0x81, (byte) 0x41, (byte) 0x90, (byte) 0xA2, (byte) 0x8A,
            (byte) 0x45, (byte) 0x81, (byte) 0x49 };

      // 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);

      System.out.print(Arrays.equals(legacySJIS, toSJIS));

   }/*from w w  w  .j a va2 s  .co m*/
}



PreviousNext

Related