StringConverter 程序首先创建一个包含
Unicode 字符:
String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
打印时,名为 original 的字符串显示为:
AêñüC
要将 String 对象转换为 UTF-8,请调用 getBytes 方法并
指定适当的编码标识符作为参数。这
getBytes 方法返回一个 UTF-8 格式的字节数组。创建一个
来自非 Unicode 字节数组的字符串对象,调用字符串
带有编码参数的构造函数。使这些代码
调用包含在 try 块中,以防指定的编码是
不支持:
try {
byte[] utf8Bytes = original.getBytes("UTF8");
byte[] defaultBytes = original.getBytes();
String roundTrip = new String(utf8Bytes, "UTF8");
System.out.println("roundTrip = " + roundTrip);
System.out.println();
printBytes(utf8Bytes, "utf8Bytes");
System.out.println();
printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringConverter 程序打印出 utf8Bytes 和
defaultBytes 数组来演示一个重要的点:
转换后的文本可能与源的长度不同
文本。一些 Unicode 字符转换为单个字节,其他字符转换为
字节对或三元组。
printBytes 方法通过调用源文件中定义的 byteToHex 方法来显示字节数组,
UnicodeFormatter.java。这是 printBytes 方法:
public static void printBytes(byte[] array, String name) {
for (int k = 0; k < array.length; k++) {
System.out.println(name + "[" + k + "] = " + "0x" +
UnicodeFormatter.byteToHex(array[k]));
}
}
printBytes 方法的输出如下。注意只有第一个
最后一个字节,即 A 和 C 字符,在两个数组中都是相同的:
utf8Bytes[0] = 0x41
utf8Bytes[1] = 0xc3
utf8Bytes[2] = 0xaa
utf8Bytes[3] = 0xc3
utf8Bytes[4] = 0xb1
utf8Bytes[5] = 0xc3
utf8Bytes[6] = 0xbc
utf8Bytes[7] = 0x43
defaultBytes[0] = 0x41
defaultBytes[1] = 0xea
defaultBytes[2] = 0xf1
defaultBytes[3] = 0xfc
defaultBytes[4] = 0x43