【问题标题】:Android Programming: Cannot read file from file picker IntentAndroid 编程:无法从文件选择器 Intent 中读取文件
【发布时间】:2020-04-16 20:28:15
【问题描述】:

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

异常:java.io.FileNotFoundException:/document/6471(没有这样的文件 或目录)

下面是我的代码:

// 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" />

【问题讨论】:

  • 你能分享你的日志吗?
  • 当然你会得到一个找不到文件的异常,因为 .getPath() 没有给你一个文件的路径,你可以看到。使用 .toString() 获取内容方案。你是本周犯错的第 53 号,所以阅读一些标记为 android 的页面可能已经对你有所帮助。
  • 您需要从内容解析器解析 URI 以获取实际路径。您是否需要仅支持文本文件或任何 MIME 媒体类型,如图像、音频、视频?
  • @VaikundamRaghul 我只需要阅读文本文件(txt、word、pdf 等)

标签: android file kotlin io


【解决方案1】:
// 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()
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2014-02-18
    相关资源
    最近更新 更多