Java-i18n-unicode-string

提供:Dev Guides
移動先:案内検索

Java内部化-文字列とのUnicode変換

Javaでは、テキストは内部的にUnicode形式で保存されます。 入力/出力が異なる形式の場合、変換が必要です。

変換

次の例では、Unicode文字列のUTF8 byte []への変換とUTF8 byte []からUnicode byte []への変換を示します。

IOTester.java

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;

public class I18NTester {
   public static void main(String[] args) throws ParseException, UnsupportedEncodingException {

      String unicodeString = "\u00C6\u00D8\u00C5" ;

     //convert Unicode to UTF8 format
      byte[] utf8Bytes = unicodeString.getBytes(Charset.forName("UTF-8"));
      printBytes(utf8Bytes, "UTF 8 Bytes");

     //convert UTF8 format to Unicode
      String converted = new String(utf8Bytes, "UTF8");
      byte[] unicodeBytes = converted.getBytes();
      printBytes(unicodeBytes, "Unicode Bytes");
   }

   public static void printBytes(byte[] array, String name) {
      for (int k = 0; k < array.length; k++) {
         System.out.println(name + "[" + k + "] = " + array[k]);

      }
   }
}

出力

次の結果が出力されます。

UTF 8 Bytes[0] = -61
UTF 8 Bytes[1] = -122
UTF 8 Bytes[2] = -61
UTF 8 Bytes[3] = -104
UTF 8 Bytes[4] = -61
UTF 8 Bytes[5] = -123
Unicode Bytes[0] = -58
Unicode Bytes[1] = -40
Unicode Bytes[2] = -59

link:/cgi-bin/printpage.cgi [__印刷]