我遇到了unicode字符序列化和反序列化的问题。这是一个示例程序,它将char写入文件,然后尝试读取它。书写和读取字符( ch 和 ch2 )是不同的。有什么建议我为什么会出现这种行为?
public class MainClass {
public static void main(String[] args) {
try {
File outfile = new File("test.txt");
FileOutputStream fos = new FileOutputStream(outfile);
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-16");
FileInputStream fis = new FileInputStream(outfile);
InputStreamReader reader = new InputStreamReader(fis, "UTF-16");
char ch = 56000;
System.out.println(Integer.toBinaryString(ch));
writer.write(ch);
writer.close();
char ch2 = (char) reader.read();
System.out.println(Integer.toBinaryString(ch2));
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
UPD: 根据经验发现,这种情况仅适用于55296-57343范围内的数字。
答案 0 :(得分:6)
字符56000是U+DAC0,不是valid unicode character,而是high surrogate character。成对使用They指向16位宽BMP之外的字符。