3

Following code works with file having English content perfectly but not with Russian content. How to make it work for Russian as well?

try(BufferedReader fileOut = new BufferedReader(new FileReader(file))){

        for(String line; (line = fileOut.readLine()) != null; ){
            if(line.contains(commandString)) 
                System.out.println(count + ": " + line);
            count++;
        }

    }

UPD:

I tried to write: this only works when the line contains one word then outputs, for example: "привет" If a line contains more than one word is no output, for example "привет как дела"

 new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1251"))

p.s: thank very much for answers

nanosoft
  • 2,913
  • 4
  • 41
  • 61
  • 5
    Maybe: http://stackoverflow.com/questions/696626/java-filereader-encoding-issue –  Feb 02 '15 at 17:31
  • My first guess would be the code page of the `commandString` value does not match that of the file contents. You should probably provide some more information, such as sample data. – mustaccio Feb 02 '15 at 17:31
  • What character encoding is the file using? – Philipp Feb 02 '15 at 17:31

2 Answers2

2

You need to specify the encoding to be able to read the russian character. Don't use FileReader as it will use default platform encoding.

Instead use

new BufferedReader(new InputStreamReader(fileDir), "UTF8");
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • I tried to write: this only works when the line contains one word then outputs, for example: "привет" If a line contains more than one word is no output, for example "привет как дела" **new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1251"))** – Никола Нестерчук Feb 02 '15 at 17:53
0

Use below method to read file content of any file in any language. I have made a FileUtil.java and this method is a part of it. Its handy and works well...

And the key to the working code is charset:

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"))

Whole method is below:

public static String getFileContent(File file) throws IOException
    {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"))) {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
                sb.append(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
nanosoft
  • 2,913
  • 4
  • 41
  • 61