我正在使用 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);
}
FileUtils.readFileToString
不适用于 StandardCharsets.UTF_8
。
相反,尝试
FileUtils.readFileToString(customersFile, "UTF-8");
或
FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());
这就是我在 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;
}
我发现日志中一切都很好,所以我解决了休息控制器中的问题:
@GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")