安卓编程 : Cannot read file from file picker Intent

标签 android file kotlin io

我正在创建一个简单的 Android 应用程序,当用户点击一个按钮时,会出现一个文件选择器,用户可以在其中选择一个文件,然后该应用程序会读取文件的内容。但是,在我下面的代码中,在选择文件后(在实例化 File 对象的那一行)我得到了一个 FileNotFound 错误:

EXCEPTION: java.io.FileNotFoundException: /document/6471 (No such file or directory)

下面是我的代码:

// File picker implementation
private fun chooseFile(view:View) {
    println("chooseFile activated!");
    var selectFile = Intent(Intent.ACTION_GET_CONTENT)
    selectFile.type = "*/*"
    selectFile = Intent.createChooser(selectFile, "Choose a file")
    startActivityForResult(selectFile, READ_IN_FILE)
}


/* After startActivityForResult is executed, when the selectFile Intent is completed, onActivityResult is executed with
   the result code READ_IN_FILE.*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == READ_IN_FILE) { // Step 1: When a result has been received, check if it is the result for READ_IN_FILE
        if (resultCode == Activity.RESULT_OK) { // Step 2: Check if the operation to retrieve thea ctivity's result is successful
            // Attempt to retrieve the file
            try {
                // Retrieve the true file path of the file
                var uri: Uri? = data?.getData();
                // Instantiate a File object from the file name
                var file:File = File(uri?.getPath());

                // Read the file, line by line
                file.forEachLine { println(it) }
            } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                println("EXCEPTION: " + e.toString());
                Toast.makeText(this, "Sorry, but there was an error reading in the file", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var file1:Button = findViewById(R.id.file1);
    file1.setOnClickListener(::chooseFile)
}

下面是我的 XML 代码(activity_main.xml):

<Button
    android:id="@+id/file1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="sans-serif"
    android:text="File 1"
    android:textAllCaps="false"
    android:textSize="16sp" />

最佳答案

// File picker implementation
private fun chooseFile(view:View) {
    //only the below specified mime type is allowed in the picker
    val mimeTypes = arrayOf(
        "application/msword",
        "application/vnd.ms-powerpoint",
        "application/vnd.ms-excel",
        "text/plain",
        "application/pdf"
    )
    println("chooseFile activated!");
    var selectFile = Intent(Intent.ACTION_GET_CONTENT)
    selectFile.type = if (mimeTypes.size == 1) mimeTypes[0] else "*/*"
        if (mimeTypes.isNotEmpty()) {
            selectFile.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        }
    selectFile = Intent.createChooser(selectFile, "Choose a file")
    startActivityForResult(selectFile, READ_IN_FILE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 200) { // Step 1: When a result has been received, check if it is the result for READ_IN_FILE
        if (resultCode == Activity.RESULT_OK) { // Step 2: Check if the operation to retrieve thea ctivity's result is successful
            // Attempt to retrieve the file
            try {
                data?.data?.let {
                    contentResolver.openInputStream(it)
                }?.let {
                    val r = BufferedReader(InputStreamReader(it))
                    while (true) {
                        val line: String? = r.readLine() ?: break
                        println(line)
                    }
                }

            } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                Toast.makeText(
                    this,
                    "Sorry, but there was an error reading in the file",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

关于安卓编程 : Cannot read file from file picker Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491076/

相关文章:

android - 异步更新 View

android - 将 MediatorLiveData 迁移到 SharedFlow

java - 应用程序中有大量数据

Windows 主机文件和带点的主机名

java - 打开文件会产生 java.lang.NullPointerException

无法让 fwrite 正常工作

java - 我的单词搜索游戏不断崩溃,但在构建它时未检测到错误

android - 如何过滤与android room db的一对多关系

android - SharedPreferences 与私有(private)文件

android - 将 TabLayout 文本设为粗体