代码之家  ›  专栏  ›  技术社区  ›  levanovd

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

  •  4
  • levanovd  · 技术社区  · 15 年前

    我面临着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范围内的数字上。

    1 回复  |  直到 15 年前
        1
  •  6
  •   BalusC    15 年前

    字符56000是 U+DAC0 哪一个不是 valid unicode character 这是一个 high surrogate character . They 在一对中使用,以指向16位宽之外的字符 BMP .