首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileNotFoundException on FileReader

FileNotFoundException on FileReader
EN

Stack Overflow用户
提问于 2018-05-14 07:18:17
回答 1查看 61关注 0票数 0

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

我的守则:

代码语言:javascript
复制
@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");
            }
        }
    }
}

错误日志:

代码语言:javascript
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-14 07:25:11

filePath = uri.getPath();

这不是一个文件系统路径,所以难怪什么都找不到。

相反,打开一个输入流并从该流中读取。

代码语言:javascript
复制
InputStream is = getContentResolver().openInputStream(data.getData());
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50324895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档