Java 国际化 - Unicode 与字符串的转换
在 Java 中,文本以 Unicode 格式内部存储。如果输入/输出格式不同,则需要转换。
转换
以下示例将展示 Unicode 字符串与 UTF8 byte[] 的转换以及 UTF8 byte[] 与 Unicode byte[] 的转换。
示例
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" ;
//将 Unicode 转换为 UTF8 格式
byte[] utf8Bytes = unicodeString.getBytes(Charset.forName("UTF-8"));
printBytes(utf8Bytes, "UTF 8 Bytes");
//将 UTF8 格式转换为 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

