Mikhail Batcer
Mikhail Batcer

Reputation: 2065

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);
}

Upvotes: 0

Views: 10041

Answers (3)

Morningstar-
Morningstar-

Reputation: 23

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")

Upvotes: 0

Mikhail Batcer
Mikhail Batcer

Reputation: 2065

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;
}

Upvotes: 0

Guillaume F.
Guillaume F.

Reputation: 1130

FileUtils.readFileToString doesn't work with StandardCharsets.UTF_8.

Instead, try

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

or

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

Upvotes: 0

Related Questions