我遇到了unicode字符序列化和反序列化问题。这是一个示例程序,它将一个字符写入文件,然后尝试读取它。写入和读取字符(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。
在关闭输出后打开输入流时会发生什么? – thejh 2010-11-06 15:04:38
重新安排程序串没有帮助,所以这不是问题的原因。 – levanovd 2010-11-06 15:06:36