49

I'm unable to create directory in android 10. It's working on devices till android Oreo.

I tried two ways for creating folders.

Using File.mkdir():

   File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pastebin");
                    if (!f.isFile()) {
                        if (!(f.isDirectory())) {
                               success =  f.mkdir();
                        }

Here, the variable success is always false which means the directory isn't created.

Using Files.createDirectory():

   File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pastebin");
                    if (!f.isFile()) {
                        if (!(f.isDirectory())) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                try {
                                    Files.createDirectory(Paths.get(f.getAbsolutePath()));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    Toast.makeText(getApplicationContext(), R.string.unable_to_download, Toast.LENGTH_LONG).show();
                                }
                            } else {
                                f.mkdir();
                            }
                        }

which causes this exception:

pzy64.pastebinpro W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Pastebin
pzy64.pastebinpro W/System.err:     at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:391)
pzy64.pastebinpro W/System.err:     at java.nio.file.Files.createDirectory(Files.java:674)

I've implemented the run-time permissions and

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

are all set.

7 Answers 7

134

As was first disclosed back in March 2019, you no longer have access by default to arbitrary locations on external storage or removable storage on Android 10+. This includes Environment.getExternalStorageDirectory() and other methods on Environment (e.g., getExternalStoragePublicDirectory().

For Android 10 and 11, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work.

Otherwise, your choices are:

  • Use methods on Context, such as getExternalFilesDir(), 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 and ACTION_CREATE_DOCUMENT.

  • If your content is media, you can use MediaStore to place the media in standard media locations.

Sign up to request clarification or add additional context in comments.

14 Comments

are you saying that there is no way to create my own directory on Android Q?
@Xihuny: You are welcome to create subdirectories of getExternalFilesDir() and similar locations supplied by Context. You cannot create subdirectories off of the roots of external or removable storage directly, using filesystem APIs.
I don't want to do that because the files will be removed when user uninstall the app.
@Xihuny: Then use the Storage Access Framework and allow the user to choose where on the user's device you put the user's content.
@Xihuny: You can use ACTION_OPEN_DOCUMENT_TREE to allow the user to choose a document tree. From there, use DocumentFile.fromTreeUri() to get a DocumentFile for that document tree. You can then create children (documents and trees) in that tree, with whatever names you want. Whether it is a "directory" depends on what the user chooses as the base document tree -- there is no requirement that they choose something on the filesystem.
|
20

For Android 10, you can add

android:requestLegacyExternalStorage="true"

to your element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work. This fix will not work on Android R and higher though, so this is only a short-term fix.

2 Comments

unless your targetSDK >= 30 it will still work in Android 11 & beyond.
What's the long term fix for Android 11?
12

There are more restrictions in Android API 30

you can only write in your app-specific files

 File dir_ = new File(context.getFilesDir(), "YOUR_DIR");
 dir_.mkdirs();

or in the external storage of your app Android/data

File dir_ = new File(myContext.getExternalFilesDir("FolderName"),"YOUR_DIR");

UPDATE

this answer provided another solution https://stackoverflow.com/a/65744517/8195076

UPDATE

another way is to grant this permission in manifest

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

like this answer https://stackoverflow.com/a/66968986/8195076

1 Comment

Woow this has worked for me, remember to set android:requestLegacyExternalStorage="true" in your manifest
6

This works for me and I think it's functional on Android 10>

ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/Folder Example");
String path = String.valueOf(resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues));
File folder = new File(path);
boolean isCreada = folder.exists();
if(!isCreada) {
    folder.mkdirs();
}

8 Comments

getExternalStoragePublicDirectory is Deprecated in API level 29
Yes, and? As the documentation states When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible, so if you have android:requestLegacyExternalStorage="true" in your manifest, you can still use it.
Firstly, it wasn't me who downvoted. To answer your question, you are querying a file, which is not allowed on Android 10>, unless you request legacy storage. To do it correctly, you should get the Uri, like this Uri mUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); then use that Uri directly instead of passing it to a File object.
An apology, this is just how I create the Uri resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); As I said I am new programming for android but it seems to me that if it is necessary to passing to File to create the folder, sorry bad english
You do not have to create a folder. When you write to the Uri the folder gets created automatically.
|
5

You can use public directory to save files in Android 11 like this:

dir = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS).getPath()
    + "/foldername");

if (!dir.exists()) {
     dir.mkdir();
     Toast.makeText(getApplicationContext(), "not exist", Toast.LENGTH_SHORT).show();
}

2 Comments

This is working in Android 12 but not in Android 9 and 10 devices. getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS) is not available in those so replaced that with Context.getExternalFilesDir(DIRECTORY_DOCUMENTS) but no folder was created. Documents folder is not seen in Android 9 and 10
Environment.getExternalStoragePublicDirectory is deprecated on new versions, use MediaStore queries and Environment.DIRECTORY_DOCUMENTS (or the directory you require) instead
4

Since Q beta 4 it's possible to opt-out of that feature by:

targeting api 28 (or lower) using requestLegacyExternalStorage manifest attribute:

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

Comments

0

only use

android:requestLegacyExternalStorage="true"

in manifests

2 Comments

this is only for android version < android 11. Not applicable for android version greater then 10.
@user6159419 Yes and on Android 11>, File path access is once again allowed. So, android:requestLegacyExternalStorage="true" is to ensure it works on Android 10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.