不读取 utf-8 标记

Not reading utf-8 marks

我的 SD 卡上有一个带有 utf-8 标记的 .txt 文件,例如:

"Jak przetrwać wśród czarnych dziur"

这就是我尝试从这个文件中读取它们的方式:

public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
    BufferedReader in;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
        String line = null;
        while ((line = in.readLine()) != null) {
            String title = line;
            String author = in.readLine();
            String pages = in.readLine();
            String date = in.readLine();

            // just for debugging
            System.out.println(title);

            books.add(new SingleBook(title, author, pages, date));
        }
    } catch (Exception e) {
        Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
        return;
    }
}

但是它没有正确读取文件:

我做错了什么?

我认为您的问题出在这里:

in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));

应该是

in = new BufferedReader(new FileReader(new File(filePath));

这应该没看错。如果没有,您可以使用 RandomAccessFile:

public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
RandomAccessFile in;
try {
    in = new RandomAccessFile(new File(filePath), "r");
    String line = null;
    while ((line = in.readUTF8()) != null) {
        String title = line;
        String author = in.readUTF8();
        String pages = in.readUTF8();
        String date = in.readUTF8();

        // just for debugging
        System.out.println(title);

        books.add(new SingleBook(title, author, pages, date));
    }
} catch (Exception e) {
    Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
    return;
}
}