Android - Permission Denied for creating new file

前端 未结 1 1562
说谎
说谎 2021-01-19 05:49

Im trying to create a file in Android, and even after following all the other answers im still getting permission denied. Error happens in saveImage() method.



        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 05:58

    This isn't an Android permissions issue. Rather, the Exception is due to Linux permissions, though inadvertently.

    In instantiating the Files used in saveImage(), you're concatenating the name of the new file/directory to Environment.getExternalStorageDirectory(); e.g., for wallpaperDirectory:

    new File(Environment.getExternalStorageDirectory() + "TEST_APP_PHOTO_FOLDER")
    

    This is implicitly calling toString() on Environment.getExternalStorageDirectory() and directly appending the name to it without the necessary path separator in between, so you end up with a full name that's something like /storage/emulated/0TEST_APP_PHOTO_FOLDER. This refers to a file in the parent of the external storage directory, and you don't have write access there, thus the Exception.

    Simply change your File instantiations to use the constructor that takes separate File and String arguments; the first for the parent directory, and the second for the name. Basically, change the plus sign to a comma. For example:

    new File(Environment.getExternalStorageDirectory(), "TEST_APP_PHOTO_FOLDER")
    

    0 讨论(0)
提交回复
热议问题