Java – The problem of reading French words from text files in java/android

The problem of reading French words from text files in java/android… here is a solution to the problem.

The problem of reading French words from text files in java/android

I’m trying to read the contents of a French file (character by character) and check the ASCII value there to do something. Everything works fine with the English alphabet, but I’m having some problems with characters like àéèé.

For example, if my file content is français, the output I get is français.
Here I have attached my code, please review and guide me to solve this problem.

File file = new File("C:\text.txt");

fis = new BufferedInputStream(new FileInputStream(file));

char current;
char org;
while (fis.available() > 0) {
    current = (char) fis.read();  to read character
                                     from file
    int ascii = (int) current;  to get ascii for the
                                 character
    org = (char) (ascii);  to get the actual
                                 character

if (ascii == 10) {          
        resultString = resultString.append(",'"
                    + strCompCode + "'");
        dbhelpher.addDataRecord(resultString.toString());

resultString.setLength(0);
    } else if (ascii != 13) { // other than the ascii
                                 13, the character are
                                 appended with string
                                 builder
        resultString.append(org);
    }
}
fis.close();

Here I need to read the French characters in the text file.
Thank you very much for your advice. Thanks in advance.

Solution

You should use InputStreamReader and UTF8 encoding:

InputStreamReader reader = new InputStreamReader(fis, "UTF8");

I recommend that you use the Apache Commons IO library. With one line of code, you can read all lines from a file and then process them in a for loop:

List<String> lines = IOUtils.readLines(fis, "UTF8");

for (String line: lines) {
  dbhelper.addDataRecord(line + ",'" + strCompCode + "'"); 
}

You can add it to build.gradle:

dependencies {
  ...
  compile 'commons-io:commons-io:2.4'
  ...
}

Related Problems and Solutions