问题
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 asgetExternalFilesDir()
, 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
andACTION_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