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

问题描述 投票:0回答:4

我正在开发一个 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)
    }

我的响应文件选择的功能:

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()
        }
    }
}

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

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

android file exception kotlin filenotfoundexception
4个回答
16
投票

您没有收到文件路径,您收到了

Uri
。您必须使用
Uri
基于 API,例如
ContentResolver.openInputStream()
来访问该
Uri
的内容,因为 Android 不会授予您的应用直接
File
访问基础文件(它也可以从 Google 云端硬盘流式传输或直接从互联网下载,而您的应用程序并不知道正在发生这种情况):

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()
        }
    }
}

这里我们可以假设我们通过将正确的 mime 类型传递给我们的请求来获得正确格式的内容(因为不要求文本文件以

.txt
扩展名作为其路径的一部分):

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

startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)

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


8
投票

如果您在 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;
                }

我已经解决了这个问题,它在 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();
                }
            }
        }
    }

这里的 TEMP_FILE 值为“temp”。


5
投票

您不能在转换为字符串的

ÙRI
上打开 Java 文件,URI 的“路径”部分与物理文件位置无关。

使用

contentResolver
获取 Java
FileDescriptor
来打开文件。

val parcelFileDescriptor: ParcelFileDescriptor =
            contentResolver.openFileDescriptor(uri, "r")
    val fileDescriptor: FileDescriptor = parcelFileDescriptor.fileDescriptor

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

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


1
投票

打开给定 URI 的位图文件:

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor =
            getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}
© www.soinside.com 2019 - 2024. All rights reserved.