'FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic
I am using FileUtils.readFileToString to read contents of a text file with JSON at once. The file is UTF-8 encoded (w/o BOM). Yet, instead of cyrillic letters I get ?????? signs. Why?
public String getJSON() throws IOException
{
File customersFile = new File(this.STORAGE_FILE_PATH);
return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
}
Solution 1:[1]
FileUtils.readFileToString doesn't work with StandardCharsets.UTF_8.
Instead, try
FileUtils.readFileToString(customersFile, "UTF-8");
or
FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());
Solution 2:[2]
This is how I solved it back in 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;
}
Solution 3:[3]
I figured out that in logs all was fine, so I solved problem in rest controller:
@GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mikhail Batcer |
| Solution 3 | Morningstar- |
