【问题标题】:Can't open csv file with Buffered Reader无法使用缓冲读取器打开CSV文件
【发布时间】:2015-05-08 13:26:57
【问题描述】:

我正在尝试读取我的 res/raw/friends.csv 中的 csv 文件,并将其逐条导入我的数据库中。但是,我的函数的第 3 行似乎无法找到或打开文件并以 javaNULLPointerException 退出。我该怎么办?

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

【问题讨论】:

  • 你确定你的相对路径是正确的吗?如果不确定,为什么不直接使用完整路径?如果正确,则可能是您尝试读取的文件的权限问题。
  • @ksealey 那么它应该是什么样子?
  • 从根开始。如果您在 Windows 上,请右键单击要打开的文件,单击“属性”,它将显示从 C: 或任何驱动器开始的绝对位置
  • @ksealey 我在 Mint 上做。甚至像这样 in = new BufferedReader(new FileReader("/home/andrey/AndroidStudioProjects/whatever/app/src/main/res/raw/friends.csv"));它仍然给出相同的异常
  • 那么这可能是权限问题。如果您在 linux 上,我会将用户和组更改为 bin (sudo chown -R bin:bin /home/andrey/AndroidStudioProjects/whatever/app/src/main/res/raw/),并将每个人的读写操作 (sudo chmod -R ugo+rw ) 添加到包含文件和任何子目录的目录中

标签: java android sql database csv


【解决方案1】:

首先,你应该只有一个大的 try-catch 块,而不是两个;如果第一次失败,第二次总是会失败并返回 NullPointerException。

其次,您不能使用文件名和路径来访问 Android 应用中的资源。这仅适用于桌面 Java 程序。

您必须使用 getResources().openRawResource()

这是您的代码的工作版本:

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

【讨论】:

  • “无法解析方法 getResources()”,并且没有提供用于导入类或其他内容的选项
  • getResources() 是来自 Activity 类(实际上是它的超类 Context)的方法。您需要代码中的 Context 才能访问应用程序的文件
猜你喜欢
  • 2016-01-23
  • 2021-12-10
  • 2011-09-15
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多