将字符保存到文件时出现问题

时间:2010-11-06 14:51:31

标签: java file unicode character-encoding char

我遇到了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范围内的数字。

1 个答案:

答案 0 :(得分:6)

字符56000是U+DAC0,不是valid unicode character,而是high surrogate character。成对使用They指向16位宽BMP之外的字符。