【问题标题】:'No such file or directory' error on Filereader - AndroidFilereader 上的“没有这样的文件或目录”错误 - Android
【发布时间】:2016-04-21 01:27:44
【问题描述】:

我正在尝试在我的 Android 上的 SQLite 数据库中导入 CSV,目的是让用户选择 CSV 文件。

我收到一个 ENOENT 错误:FileReader file = new FileReader(fileName);

该文件确实存在,因为我从意图中获得了路径!

我的清单包括:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

我的意图

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/csv");
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(intent, REQUEST_CVS);

我的 onActivityResult(...)

if (resultCode == RESULT_OK) {
   File myPath_CSV = new  File(data.getData().toString());
   try {
       myDb.importCSV(myPath_CSV);
   } catch (IOException e) {
      e.printStackTrace();
   }
}

我的 importCSV(fileName)

public void importOreilles(File fileName) throws IOException {
    Log.w(TAG, fileName.toString());
    FileReader file = new FileReader(fileName);   // Getting an error !!!
    BufferedReader buffer = new BufferedReader(file);

    String line = null;
    while ((line = buffer.readLine()) != null) {
        String[] str = line.split(",");
        insertOreille(str[0],str[1]);  // Dealing with my database
    }
}

我遇到的错误

W/DBAdapter: file:/storage/emulated/0/Download/Oreilles.csv
W/System.err: java.io.FileNotFoundException: /file:/storage/emulated/0/Download/ABCDE.csv: open failed: ENOENT (No such file or directory)

我尝试使用 getAbsolutePath、Uri、File... 但我卡住了。

任何帮助表示赞赏。

【问题讨论】:

    标签: java android


    【解决方案1】:

    该文件确实存在,因为我从意图中获得了路径!

    您决定不提供实际的“意图”以及您如何使用它。我猜是ACTION_GET_CONTENT。在这种情况下,你会得到一个Uri (data.getData())。 Use ContentResolver and openInputStream() 读取Uri 指向的内容。您可以将其包装在 InputStreamReader 中,以便与现有的基于 Reader 的代码一起使用。

    【讨论】:

    • 刚刚添加了我的意图(确实是 Intent.ACTION_GET_CONTENT)
    • @Tibo:您返回的Uri 可能有filecontent 方案。 ContentResolveropenInputStream() 将处理这两种情况,假设在 file 的情况下,the user granted you permission
    • 从您的链接中,我认为我的问题是我对什么是 Uri 缺乏了解。我要去看看 openInputStream。
    • 我还是迷路了。假设我使用InputStream is = getContentResolver().openInputStream(Uri_CSV)。我应该如何使用is 来读取 CSV 文件的行?
    • @Tibo:正如我在回答中所写,您可以将其包装在 InputStreamReader 中,以便与您现有的 CSV 代码一起使用。或者,使用 CSV 库。
    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多