在Java/Android中从文本文件读取法语单词出现问题

4
我正在尝试读取一个法语文件的内容(逐个字符),并检查它们的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
文本文件使用的编码方式是什么?看起来你应该使用一个正确编码(可能是UTF-8)的InputStreamReader,并且逐行读取。请注意,ASCII不包括任何带重音的字符。此外,请在以后更加注重格式化你的源代码。 - Jon Skeet
请查看此链接,它是关于读取UTF-8文件的:http://www.mkyong.com/java/how-to-read-utf-8-encoded-data-from-a-file-java/ - Jure
是的,我的文本文件使用UTF-8编码。 - Pranesh Sahu
我查看了你提到的链接,但发现有些东西我无法在我的代码中实现,即in.readLine()。你能帮忙吗? - Pranesh Sahu
@PraneshSahu 请保持良好的代码格式,并且不要添加与你的问题无关的代码。 - mixel
如果我的回答有帮助,请考虑点赞或接受它,谢谢。 - mixel
1个回答

4
您应该使用带有UTF8编码的InputStreamReader:
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'
  ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接