[英]Can't open csv file with Buffered Reader
I'm trying to read the csv file which is in my res/raw/friends.csv and import it record by record in my database. 我正在尝试读取我的res / raw / friends.csv中的csv文件,并在我的数据库中按记录导入它。 However, 3rd line of my function seems to unable to either locate or open the file and exiting with javaNULLPointerException. 但是,我的函数的第3行似乎无法找到或打开文件并退出javaNULLPointerException。 What should I do? 我该怎么办?
public void fillBase(SQLiteDatabase db){
BufferedReader in=null;
try {
in = new BufferedReader(new FileReader("raw/friends.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace(); //end up going here!
}
String line = null;
try {
while ((line = in.readLine()) != null) {
String[] parts = line.split(",");
ContentValues values = new ContentValues();
values.put("Name", parts[0]);
// Insert the data into the database
db.insert(FRIENDS, null, values); // insert your table name
}
} catch (IOException e) {
e.printStackTrace();
}
}
First, you should have just one big try-catch block and not two; 首先,你应该只有一个大的试试块而不是两个; if the first fail the 2nd will always fail with a NullPointerException. 如果第一次失败,第二次将始终失败,并出现NullPointerException。
Second, you can't use file names and paths to access resources in an Android app. 其次,您无法使用文件名和路径访问Android应用中的资源。 That only works for desktop Java programs. 这仅适用于桌面Java程序。
Instead you must use getResources().openRawResource() 相反,你必须使用getResources()。openRawResource()
Here's a working version of your code: 这是您的代码的工作版本:
public void fillBase(SQLiteDatabase db){
try {
BufferedReader in= new BufferedReader(getResources().openRawResource(R.raw.friends));
String line = null;
while ((line = in.readLine()) != null) {
String[] parts = line.split(",");
ContentValues values = new ContentValues();
values.put("Name", parts[0]);
// Insert the data into the database
db.insert(FRIENDS, null, values); // insert your table name
}
} catch (IOException e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.