I have this method reading the file:

private String fileContent = ""; void writeFile(String path) { try (FileInputStream input = new FileInputStream(path)) { int stream = input.read(); while (stream != -1) { this.fileContent = String.format("%s%s", this.fileContent, ((char)stream)); stream = input.read(); } } catch (IOException e) { e.printStackTrace(); } } 

When I read the English alphabet from a file, everything is ok. But when I try to count Cyrillic, hieroglyphs are obtained. Although in the file from which I read the UTF-8 encoding and in the development environment I have UTF-8. Tell me how to fix it?

1 answer 1

Decided like this. Maybe someone else will be useful. Immediately from the file to the required encoding.

  private String fileContent = ""; private void writeFile() { try (BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(this.path), "UTF-8"))) { String sub; while ((sub = br.readLine()) != null) { this.fileContent = String.format("%s%s\n", this.fileContent, sub); } } catch (IOException e) { e.printStackTrace(); } } 
  • one
    If Java version> = 1.7, then StandardCharsets can be used: new InputStreamReader(new FileInputStream(this.path, StandardCharsets.UTF_8)); - Sergi
  • And cool! Thanks, I'll keep it in mind. - Pavel