Android Kotlin:使用从文件选择器中选择的文件名获取 FileNotFoundException?

Cal*_*ies 7 android exception file filenotfoundexception kotlin

我正在开发一个 Android 应用程序,其中一项功能是让用户选择要打开的文件(我想打开纯文本 .txt 文件)。我之前使用 Java 开发过 Android 应用程序,但对于这个应用程序,我使用的是 Kotlin,这是我第一次使用 Kotlin。

我目前让应用程序显示一个文件选择器,让用户点击他们想要打开的文件。然后我尝试使用 File 对象打开文件并执行 forEachLine 循环。但出于某种原因,它抛出一个 java.io.FileNotFoundException (没有这样的文件或目录)与从文件选择器中选择的文件。我不确定出了什么问题,是否必须进行一些转换才能转换文件路径?

我的“加载”按钮的代码:

val btn_load: Button = findViewById<Button>(R.id.btn_load_puzzle)
    btn_load.setOnClickListener {
        val intent = Intent()
            .setType("*/*")
            .setAction(Intent.ACTION_GET_CONTENT)

        startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    }
Run Code Online (Sandbox Code Playgroud)

我响应文件选择的功能:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Selected a file to load
    if ((requestCode == 111) && (resultCode == RESULT_OK)) {
        val selectedFilename = data?.data //The uri with the location of the file
        if (selectedFilename != null) {
            val filenameURIStr = selectedFilename.toString()
            if (filenameURIStr.endsWith(".txt", true)) {
                val msg = "Chosen file: " + filenameURIStr
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT)
                toast.show()
                File(selectedFilename.getPath()).forEachLine {
                    val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
                    toast.show()
                }
            }
            else {
                val msg = "The chosen file is not a .txt file!"
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
                toast.show()
            }
        }
        else {
            val msg = "Null filename data received!"
            val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
            toast.show()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

FileNotFound 异常在它创建 File 对象以执行 forEachLine 循环的行上抛出:

java.lang.RuntimeException: 未能传递结果 ResultInfo{who=null, request=111, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/0000-0000:Sudoku 谜题/hard001.txt flg=0x1 }} 到活动 {com.example.sudokusolver/com.example.sudokusolver.MainActivity}: java.io.FileNotFoundException: /document/0000-0000:Sudoku Puzzles/hard001.txt(没有这样的文件或目录)

ian*_*ake 10

您没有收到文件路径,而是收到了Uri. 您必须使用Uri基于 API 的 APIContentResolver.openInputStream()来访问其中的内容,Uri因为 Android 不允许您的应用直接File访问底层文件(它也可以从 Google Drive 流式传输或直接从互联网下载,而您的应用并不知道这是发生):

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Selected a file to load
    if ((requestCode == 111) && (resultCode == RESULT_OK)) {
        val selectedFilename = data?.data //The uri with the location of the file
        if (selectedFilename != null) {
            contentResolver.openInputStream(selectedFilename)?.bufferedReader()?.forEachLine {
                val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
                toast.show()
            }
        } else {
            val msg = "Null filename data received!"
            val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
            toast.show()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们可以假设我们通过将正确的 mime 类型传递给我们的请求来获得正确格式的内容(因为没有要求文本文件完全以.txt扩展名作为其路径的一部分):

val intent = Intent()
    .setType("text/*")
    .setAction(Intent.ACTION_GET_CONTENT)

startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
Run Code Online (Sandbox Code Playgroud)

这将自动使任何非文本文件无法被选择。


SAN*_*NAT 9

如果您在 URI 中收到“msf:xxx”,请使用以下解决方案,我在应用程序缓存目录中创建了临时文件,并在完成任务后删除了同一文件:

if (id != null && id.startsWith("msf:")) {
                    final File file = new File(mContext.getCacheDir(), Constant.TEMP_FILE + Objects.requireNonNull(mContext.getContentResolver().getType(imageUri)).split("/")[1]);
                    try (final InputStream inputStream = mContext.getContentResolver().openInputStream(imageUri); OutputStream output = new FileOutputStream(file)) {
                        final byte[] buffer = new byte[4 * 1024]; // or other buffer size
                        int read;

                        while ((read = inputStream.read(buffer)) != -1) {
                            output.write(buffer, 0, read);
                        }

                        output.flush();
                        return file;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    return null;
                }
Run Code Online (Sandbox Code Playgroud)

我已经解决了这个问题,对于 msf 来说它可以 100% 工作。:)

完成工作后还要删除临时文件:

private void deleteTempFile() {
        final File[] files = requireContext().getCacheDir().listFiles();
        if (files != null) {
            for (final File file : files) {
                if (file.getName().contains(Constant.TEMP_FILE)) {
                    file.delete();
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里的 TEMP_FILE 值为“temp”。


And*_*rew 5

您无法打开 Java 文件\xc3\x99RI,URI 的“路径”部分与物理文件位置无关。

\n\n

使用 acontentResolver获取 JavaFileDescriptor获取用于打开文件的

\n\n
val parcelFileDescriptor: ParcelFileDescriptor =\n            contentResolver.openFileDescriptor(uri, "r")\n    val fileDescriptor: FileDescriptor = parcelFileDescriptor.fileDescriptor\n
Run Code Online (Sandbox Code Playgroud)\n\n

此方法兼容Android 10,其中非App私有目录的文件路径不可用。

\n\n

https://developer.android.com/training/data-storage/shared/documents-files

\n