Android: 使用隐式意图读取 txt 文件

Android: Reading txt file using implicit intent

问题:我正在尝试使用隐式 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 中的文件时,它说没有这样的目录。

我在这里做错了什么?

When I try to open the file with file path from Uri's getPath() and create a BufferedReader object to read from the text file, I get an error says that such file path does not exist.

那是因为ACTION_GET_CONTENT没有return一个文件。它 return 是一个 Uri,并且 Uri 不必指向文件。

摆脱所有 File 东西。使用 ContentResolveropenInputStream() 得到 InputStreamUri 识别的内容。使用 InputStream.

阅读您的文本