【问题标题】:Not reading utf-8 marks不读取 utf-8 标记
【发布时间】:2016-02-09 16:48:51
【问题描述】:

我的 sdcard 上有一个带有 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;
    }
}

但它没有正确读取文件:

我做错了什么?

【问题讨论】:

    标签: android utf-8 textview inputstream bufferedreader


    【解决方案1】:

    我相信您的问题在这里:

    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;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多