【问题标题】:Android: Reading txt file using implicit intentAndroid:使用隐式意图读取 txt 文件
【发布时间】:2016-10-02 21:17:46
【问题描述】:

问题:我正在尝试使用隐式 Intent(ACTION_GET_CONTENT) 打开一个 txt 文件并将 txt 文件的内容存储到一个数组列表中。当我尝试使用 Uri 的 getPath() 的文件路径打开文件并创建一个 BufferedReader 对象以从文本文件中读取时,我收到一条错误消息,指出此类文件路径不存在。

在 Logcat 中,它说我的文件路径是 "/document/1505-2A0C:Download/text.txt" 当我尝试打开文件时,它说:

"W/System.err: java.io.FileNotFoundException:
        /document/1505-2A0C:Download/text.txt: open failed: 
        ENOENT (No such file or directory)"

这是我的代码:

@Override
public void onClick(View v) {
    // Send implicit intent to load a file from directory
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/plain");
    startActivityForResult(Intent.createChooser(intent, 
           "Load a file from directory"), REQUEST_CODE_SEARCH);
}

onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_SEARCH) {
        try {
            Uri uri = data.getData();
            String filepath = uri.getPath();

            // In logcat : File path: /document/1505-2A0C:Download/text.txt
            Log.d("File path", filepath);

            File file = new File(filepath);
            ArrayList<String> strings = new ArrayList<>();

            /* Problem occurs here : I do not get correct file path to open a FileReader.
            In logcat: "W/System.err: java.io.FileNotFoundException:
            /document/1505-2A0C:Download/text.txt: open failed: 
            ENOENT (No such file or directory)"*/
            BufferedReader br = new BufferedReader(new FileReader(file));

            // Rest of code that converts txt file's content into arraylist
        } catch (IOException e) {
            // Codes that handles IOException
        }
    }
}

总结:我得到"/document/1505-2A0C:Download/text.txt"作为文件路径,当我使用文件路径打开BufferedReader中的文件时,它说没有这样的目录。

我在这里做错了什么?

【问题讨论】:

    标签: android android-intent bufferedreader


    【解决方案1】:

    当我尝试使用 Uri 的 getPath() 中的文件路径打开文件并创建一个 BufferedReader 对象以从文本文件中读取时,我收到一条错误消息,指出此类文件路径不存在。

    那是因为ACTION_GET_CONTENT 不返回文件。它返回一个Uri,并且Uri 不必指向一个文件。

    摆脱所有File 的东西。使用ContentResolveropenInputStream()Uri 标识的内容上获得InputStream。使用 InputStream 读入您的文本。

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多