Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?

后端 未结 3 1032
眼角桃花
眼角桃花 2020-11-22 01:13

I\'m working on an Android application where one of the features is to let the user choose a file to open (I\'m wanting to open a plain text .txt file). I\'ve worked on And

3条回答
  •  Happy的楠姐
    2020-11-22 01:39

    You did not receive a file path, you received a Uri. You have to use Uri based APIs such as ContentResolver.openInputStream() to access the contents at that Uri as Android does not grant your app direct File access to the underlying file (it could also be streamed from Google Drive or downloaded directly from the internet without your app being aware that this is happening):

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

    Here we can assume we get contents of the proper format by passing in the proper mime type to our request (as there is no requirement that a text file end in exactly the .txt extension as part of its path):

    val intent = Intent()
        .setType("text/*")
        .setAction(Intent.ACTION_GET_CONTENT)
    
    startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    

    Which will automatically make any non text file unable to be selected.

提交回复
热议问题