从java / android中的文本文件中读取法语单词的问题

时间:2015-09-28 10:54:54

标签: java android fileinputstream bufferedinputstream

我正在尝试读取法语文件内容(逐个字符)并检查ascii值以进行某些操作。一切正常,包含英文字母,但对于像àéèé这样的字符,我正面临一些问题。

例如,如果我的文件内容是français,我的输出为français。 在这里,我附上我的代码请看看并指导我解决这个问题。

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

这里我需要读取文本文件中的法语字符。 非常感谢您的建议。谢谢。

1 个答案:

答案 0 :(得分:4)

您应该InputStreamReader使用UTF8编码:

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

我建议你使用Apache Commons IO库。使用一行代码,您可以读取文件中的所有行,然后在for循环中处理它们:

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

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

您可以在build.gradle中添加:

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