我的SD卡上有一个.txt文件,上面带有utf-8标记:
“ Jakprzetrwaćwśródczarnych 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;
}
}