android kotlin java.io.FileNotFoundException: /storage/emulated/0/number.txt: open failed: EACCES (Permission denied)

孤人 提交于 2021-01-10 01:38:33

问题


I'm writing an app for Android 10 using kotlin. The app has to read file named number.txt from internal storage.

But it always fails to do so:

java.io.FileNotFoundException: /storage/emulated/0/number.txt: open failed: EACCES (Permission denied)

Here what I have in my manifest:

...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...

I have to only read the file, so there is no write permission in manifest.

Here is my code, as you can see I use runtime permissions:

This is the function that requests permission and if it granted, reads the file:

    private fun setupPermissions() {
        val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
        if (permission == PackageManager.PERMISSION_GRANTED) {
            val path = "/storage/emulated/0"
            val file = File("$path/number.txt")
            val pln = file.readText()
            plnText.text = pln
        }
        else{
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 101)
        }
    }

Then I call setupPermissions in my onCreate method.

That's it, I don't understand why isn't it working.

Thanks.

EDIT

I don't know what is the reason, but I just changed my code to this:

if (permission == PackageManager.PERMISSION_GRANTED) {
    val file = File("/storage/emulated/0/number.txt")
    val pln = file.readText()
    Log.i("IKO_APP", pln)
//  plnText.text = path.toString()
}

And it works without any error! I'm wondering though why?


回答1:


For Android 10, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your external storage code should work.

And for read operations, you should be able to still do what you are doing on Android 11+, courtesy of the "raw paths" change, even after you raise your targetSdkVersion to 30 or higher.

However, for write operations, you have until the second half of 2021 to switch to something else:

  • Use methods on Context, such as getExternalFilesDir(), to get at directories on external storage into which your app can write. You do not need any permissions to use those directories on Android 4.4+. However, the data that you store there gets removed when your app is uninstalled.

  • Use the Storage Access Framework, such as ACTION_OPEN_DOCUMENT and ACTION_CREATE_DOCUMENT.

  • If your content is media, you can use MediaStore to place the media in standard media locations.



来源:https://stackoverflow.com/questions/64119230/android-kotlin-java-io-filenotfoundexception-storage-emulated-0-number-txt-op

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!