【问题标题】:FileNotFoundException on FileReaderFileReader 上的 FileNotFoundException
【发布时间】:2018-05-14 07:18:17
【问题描述】:

我的应用程序需要选择一个 .txt 文档,将其打开并逐行读取。我可以获取文件路径没有问题,但是FileReader不会打开文件,抛出FileNotFoundException。

我的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case ACTIVITY_CHOOSE_FILE: {
            if (resultCode == RESULT_OK){
                Uri uri = data.getData();
                filePath = uri.getPath();
                if (filePath != ""){
                    txtvFileSelected.setText(filePath);
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(filePath);
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = null;
                                new BufferedReader(fileReader);
                        int currentLine = 0;
                        while((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            //TODO: add string separation into floats here.
                            currentLine++;
                        }
                        // Always close files.
                        bufferedReader.close();
                    }
                    catch(FileNotFoundException ex) {
                        System.out.println("File not found '" + filePath + "'");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else
                    txtvFileSelected.setText("No file selected");
            }
        }
    }
}

错误日志:

05-14 09:14:51.409 24212-24279/com.examens.gilian.robotapplication OpenGLRenderer: Initialized EGL, version 1.4
05-14 09:14:53.428 24212-24279/com.examens.gilian.robotapplication D/OpenGLRenderer: endAllActiveAnimators on 0xb8ad5368 (RippleDrawable) with handle 0xb8988670
05-14 09:14:59.046 24212-24212/com.examens.gilian.robotapplication I/System.out: File not found '/document/primary:media/Data.txt'

【问题讨论】:

  • filePath = uri.getPath();。那不是文件系统路径。无法使用。
  • 而且也没有“和/或”之分,或者“想不通”。异常由FileReader 抛出。 BufferedReader 那时甚至不存在。并且请注意,您在构建它时将其丢弃,因此当您解决此问题时,您将得到一个 NPE 试图调用readLine()

标签: java android filereader


【解决方案1】:

filePath = uri.getPath();

那不是文件系统路径,难怪什么都找不到。

而是打开一个输入流并从该流中读取。

InputStream is = getContentResolver().openInputStream(data.getData());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 2011-03-07
    • 2016-08-06
    • 2013-01-11
    • 2011-10-25
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多