I have an interface and a method in it

void setSource (FileInputStream fis) throws IOException; 

I implemented this method:

 @Override public void setSource(FileInputStream fis) throws IOException { StringBuffer stringBuffer = new StringBuffer(); int i = -1; while ((i = fis.read()) != -1) { stringBuffer.append((char)i); } this.text = stringBuffer.toString(); } 

And this implementation works only with Latin characters, and Cyrillic is displayed crookedly. How to fix it?

    3 answers 3

    You must specify the file encoding

     @Override public void setSource(FileInputStream fis) throws IOException { StringBuilder stringBuilder = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8)) { int i = -1; while ((i = fis.read()) != -1) { stringBuilder.append((char)i); } } this.text = stringBuilder.toString(); } 

    And do not use StringBuffer , it is slow and outdated .

    • Thanks for the advice about StringBuilder, but your implementation also unfortunately did not help to change the encoding, but pushed the idea - Yevgeny Ryabyshev

    Try to specify the encoding.

     @Override public void setSource(FileInputStream fis) throws IOException { UnicodeReader ur = new UnicodeReader(fis, "CP1251"); BufferedReader br = new BufferedReader(ur); final StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) sb.append(line); this.text = sb.toString(); } 
    • It looks like it didn’t help much, incompatible types: java.io.FileInputStream cant be converted to com.sun.tools.javac.parser.ScannerFactory - Eugene Ryabyshev

    Thanks for the help, but here's what I came up with:

     @Override public void setSource(FileInputStream fis) throws IOException { StringBuilder stringBuffer = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(fis, "UTF8")); String str; while ((str = in.readLine()) != null) { stringBuffer.append(str); } this.text = stringBuffer.toString(); in.close(); } 
    • If you wrap your code in try / catch, using in.close () is optional. Resource automatically release itself. Your main problem was the lack of knowledge of the encoding of the input stream. All answers are correct. - Rootware