【问题标题】:how to parse unicode that is read from a file in java [duplicate]如何解析从java中的文件读取的unicode [重复]
【发布时间】:2011-05-16 12:47:11
【问题描述】:

我写了一个文本文件,内容如下:\u0032\u0142o\u017Cy\u0142

然后我使用 FileReader 和 BufferedReader 来读取文件。

public static void main(String[] args) throws Exception{
   FileInputStream fr = new FileInputStream("README.TXT");
   BufferedReader br = new BufferedReader(new InputStreamReader(fr,"UTF-8"));
   String s="";
   while((s=br.readLine())!=null){
      System.out.println(s);
    }
}

但输出是:\u0032\u0142o\u017Cy\u0142

我用的时候

System.out.println("\u0032\u0142o\u017Cy\u0142");

这些代码将被解析并以正确的形式显示。

如何更改我的代码,以便文件中的 unicode 也将被解析并以正确的形式显示?

【问题讨论】:

  • 您的文件是否包含“\u0032”的实际字符,还是包含文字字符串“\u0032”?
  • 感谢您的快速回复。它包含 \u0032\u0142o\u017Cy\u0142 不带引号。

标签: java unicode utf-8 text-files fileinputstream


【解决方案1】:

您想使用sun.tools.native2ascii 对文本进行反向转换。

new sun.tools.native2ascii.Main().convert(new String[]{"-reverse", new File("README.TXT"), convertedFile});

所以这样的事情就可以了。

public static void main(String[] args) throws Exception{
   File convertedFile = new File("converted.txt");
   new sun.tools.native2ascii.Main().convert(new String[]{"-reverse", new File("README.TXT"), convertedFile});
   FileInputStream fr = new FileInputStream(convertedFile);
   BufferedReader br = new BufferedReader(new InputStreamReader(fr,"UTF-8"));
   String s="";
   while((s=br.readLine())!=null){
      System.out.println(s);
    }
}

【讨论】:

    【解决方案2】:

    您可以使用here 发布的源代码进行转义。

    【讨论】:

      【解决方案3】:

      Unicode 转义序列的解析不是 Java 标准 API 的显式部分,它仅在加载 Properties 时隐式发生。你可以从Properties的源代码中复制实现。

      但最好为您的文件使用像 UTF-8 这样的普通编码。

      【讨论】:

        猜你喜欢
        • 2017-07-08
        • 2016-03-14
        • 1970-01-01
        • 2017-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        相关资源
        最近更新 更多