Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to write an Android App that, among other things, needs to read and write files to "external" storage.

While I am able to browse and select a folder on external storage, every time I try to access the file, I get a Permission denied I/O exception.

I HAVE included the following permissions in my app's manifest:

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

I have also enabled the STORAGE permission for the app in Android.

I am developing on a Chromebook, so I do not have access to emulators. So I test and debug my app on my phone (a Pixel 3), via a USB-C cable. I can also generate an APK and sideload it on my Chromebook, but I can not debug this way.

The following code sample was one I gathered from the Internet.

 public void writeFileExternalStorage(View view) {
        String cashback = "Get 2% cashback on all purchases from xyz 
 Get 10% cashback on travel from dhhs shop";
        String state = Environment.getExternalStorageState();
        //external storage availability check
        if (!Environment.MEDIA_MOUNTED.equals(state)) {
            return;
        }
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), filenameExternal);


        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            //second argument of FileOutputStream constructor indicates whether to append or create new file if one exists
            outputStream = new FileOutputStream(file, true);

            outputStream.write(cashback.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

When the file.createNewFile() is executed, The following exception is thrown: java.io.IOException: Permission denied

I have been banging my head against the wall for two days on this issue, and it's not doing any good. I hope someone here can help, as my head really hurts! :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
200 views
Welcome To Ask or Share your Answers For Others

1 Answer

Apparently, Android 10 is to blame.

I lowered the Target SDK to 28 (Android 9) and the code works.

It looks like if I want this to work for Android 10, I will have to use MediaStore for SDK 29+.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...