'Can't access external storage in API-29

The following code works well in the lower API-29. But when using API-29, it gives access denied to external storage error.

public void persistFile(byte[] bytes, String path, String fileName) throws IOException {
    OutputStream fOut = null;
    File picDirectory = new File(path);
    File file = new File(path, fileName); 
    fOut = new FileOutputStream(file);
    fOut.write(bytes); 
    fOut.flush();  
    fOut.close();  
}

AndroidManifest.xml

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


Solution 1:[1]

On Android 10 file paths outside of your App's private directories are worthless by default, you can temporarily enable requestLegacyExternalStorage until Android 11 (which is now out in preview)

See https://developer.android.com/training/data-storage

Going forward it is probably best just to use Media Store or Storage Access Framework

https://developer.android.com/training/data-storage/shared

Solution 2:[2]

Add android:requestLegacyExternalStorage="true" in manifest application tag.

<manifest ... >
  <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew
Solution 2 mahdi