Permission denied when creating new file on external storage

Recently in API level 29, they have changed the way of accessing external storage. If you are trying to access public folders(i.e. Downloads) it will throw permission denied error.

You need to specify below code in your application tag in Manifest file.

android:requestLegacyExternalStorage="true"

Or you can save files in the root directory to avoid this error.


In my case it was due to the Permissions popup required for API 23+, even if u have added permission in the manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

Call this function when the app launches or when you need the permission.

AndroidManifest.xml

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

Detailed sample code for permissions can be found here.


Do f.mkdirs() before f.createNewFile(). You are probably trying to create a new file in a non-existent directory