【问题标题】:FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic来自 Apache Commons IO 的 FileUtils.readFileToString() 无法正确使用 Cyrillic
【发布时间】:2015-02-12 13:32:24
【问题描述】:

我正在使用 FileUtils.readFileToString 一次读取带有 JSON 的文本文件的内容。该文件采用 UTF-8 编码(无 BOM)。然而,我得到的不是西里尔字母??????迹象。为什么?

public String getJSON() throws IOException
{
    File customersFile = new File(this.STORAGE_FILE_PATH);
    return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
}

【问题讨论】:

  • 你在哪里看到???而不是西里尔语?安慰? IDE?其他文件?
  • @StephaneM 这个问题应该基本上回答了他的问题:D
  • @StephaneM 我使用 Spring Framework 构建了一个小型 REST 服务。 ????s 被返回以响应 GET 请求。然而,它们只是代替西里尔字母。
  • 你没有回答我的问题。您在哪里阅读 GET 请求的响应?
  • 浏览器中的字体是否有西里尔字符的字形(并且编码设置为 UTF-8)?

标签: java encoding cyrillic fileutils


【解决方案1】:

FileUtils.readFileToString 不适用于StandardCharsets.UTF_8

相反,试试

FileUtils.readFileToString(customersFile, "UTF-8");

FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());

【讨论】:

  • 好吧,FileUtils.readFileToString 有一个变体,它接受Charset,那么为什么不接受StandardCharsets.UTF_8?很久以前我已经用另一种方法解决了这个问题,但是有空我可能会再看看。
【解决方案2】:

这就是我在 2015 年解决它的方法:

public String getJSON() throws IOException
{
//    File customersFile = new File(this.STORAGE_FILE_PATH);
//    return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
    String JSON = "";
    InputStream stream = new FileInputStream(this.STORAGE_FILE_PATH);
    String nextString = "";
    try {
        if (stream != null) {
            InputStreamReader streamReader = new InputStreamReader(stream, "UTF-8");
            BufferedReader reader = new BufferedReader(streamReader);
            while ((nextString = reader.readLine()) != null)
                JSON = new StringBuilder().append(JSON).append(nextString).toString();
        }
    }
    catch(Exception ex)
    {
        System.err.println(ex.getMessage());
    }
    return JSON;
}

【讨论】:

    【解决方案3】:

    我发现在日志中一切都很好,所以我在休息控制器中解决了问题:

     @GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多