我面临着Unicode字符序列化和反序列化的问题。下面是一个示例程序,它将一个字符写入文件,然后尝试读取它。读写字符(
中国
和
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范围内的数字上。