StringEscapeUtils.unescapeHtml对从文件读取的字符串不起作用

时间:2013-05-14 19:01:27

标签: java file-io unicode

我正在尝试读取包含unicode字符的文件,将这些字符转换为相应的符号,然后将生成的文本打印到新文件中。我正在尝试使用StringEscapeUtils.unescapeHtml来执行此操作,但这些行只是按原样打印,unicode点仍然完好无损。我通过从文件中复制一行来进行练习,从中创建一个字符串,然后在其上调用StringEscapeUtils.unescapeHtml,这非常有效。我的代码如下:

    class FileWrite 
{
 public static void main(String args[])
  {
  try{
      String testString = " \"text\":\"Dude With Knit Hat At Party Calls Beer \u2018Libations\u2019 http://t.co/rop8NSnRFu\" ";

      FileReader instream = new FileReader("Home Timeline.txt");
      BufferedReader b = new BufferedReader(instream);

      FileWriter fstream = new FileWriter("out.txt");
      BufferedWriter out = new BufferedWriter(fstream);

      out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");//This gives the desired output,
                                                                    //with unicode points converted
      String line = b.readLine().toString();

      while(line != null){
        out.write(StringEscapeUtils.unescapeHtml3(line) + "\n");
        line = b.readLine();
      }

      //Close the output streams
      b.close();
      out.close();
  }
  catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
  }
  }
}

2 个答案:

答案 0 :(得分:2)

//This gives the desired output,
//with unicode points converted
out.write(StringEscapeUtils.unescapeHtml3(testString) + "\n");

你错了。 Java unescapes在将表单构建到类文件中时,在编译时将此表单的字符串文字:

"\u2018Libations\u2019"

此代码中没有HTML 3个转义符。您选择的方法旨在转换‘形式的转义序列。

您可能需要unescapeJava方法。

答案 1 :(得分:1)

您使用平台默认编码读取和写入字符串。您希望明确指定要用作“UTF-8”的字符集:

输入流:

BufferedReader b = new BufferedReader(new InputStreamReader(
        new FileInputStream("Home Timeline.txt"),
        Charset.forName("UTF-8")));

输出流:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("out.txt"),
        Charset.forName("UTF-8")));