1

I want to create a separate directory for images saved via my app. But I don't know where my code falls short. This is what I am doing to create a new directory in the root directory of external storage:

File root = Environment.getExternalStorageDirectory();
File directory = new File(root,"MYFOLDER");
if(!directory.exists()) {
    directory.mkdirs();
}

I have already added the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> permission in my app manifest file. And I have tried this, this and this and others but nothing works.

Shreemaan Abhishek
  • 1,134
  • 1
  • 7
  • 33

2 Answers2

1

I use this which works:

private static final String IMAGE_DIRECTORY = "/mydirectory";
File Directory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);

        if (!Directory.exists()) {
            Directory.mkdirs();
        }
aryanknp
  • 1,135
  • 2
  • 8
  • 21
1

First give runtime storage permission by adding this lines, Because after android oreo you need to give runtime permission to access storage

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }

then you can use this code

File apkStorage = new File(Environment.getExternalStorageDirectory() + "/" + "TestFolder");
 if (!apkStorage.exists()) {
        apkStorage.mkdir();
        Log.e(TAG, "Directory Created.");
}

Add requestLegacyExternalStorage="true" to application tag in manifest file

Vishwajeet Barve
  • 547
  • 3
  • 10