'android mkdirs not working

i need to save an image from camera on android. i used the write external storage permission in manifest and i am using this code

File dir = new File(Environment.getExternalStorageDirectory(), "Test");
if (!dir.exists() || !dir.isDirectory())
    dir.mkdirs();

String path = dir.getAbsolutePath();
Log.d(TAG, path);                     //log show the path
File file = new File(dir.getAbsolutePath() + "/Pic.jpg");
Log.d(TAG, file.getAbsolutePath());   //again path is shown here

outStream = new FileOutputStream(file);
outStream.write(bytes);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + bytes.length);   //fail here
} catch (FileNotFoundException e) {
Log.d(TAG, "not done");                       //error is here (this exception is thrown)
} catch (IOException e) {
Log.d(TAG, "not");
} finally {  }

i also tried mkdir() instead of mkdirs() same result.

any idea what went wrong in the code?

thanks



Solution 1:[1]

Some one like me who was trying in Android10. Please use below API in manifest:

<application android:requestLegacyExternalStorage="true" ... >
    ...
  </application> 

Latest Update From Google: After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.

Solution 2:[2]

IDIOT ME! i have used the Manifest Permission but when installed the app on phone i didnt grant permission for storage!... i understand a negative on this question... but i hope if someone else face the same..check your phone permission. sorry all for inconvenience.

Solution 3:[3]

Did you put

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

in your AndroidManifest? If you are using android M you must request user permission to write on sd, look here an example

Solution 4:[4]

you have created directory, not file. Create new file with following code

File file = new File(dir.getAbsolutePath() + "/Pic.jpg");
file.createNewFile()

Solution 5:[5]

if you are testing on android M, you should probably check Settings > App > Permission to see if permission to access storage is granted. This saved me.

Solution 6:[6]

if you already allowed R/W permission(Runtime Permission too) and still doesn't work add this below mentioned line in your AndroidManifest.xml

<application ........ ........ android:requestLegacyExternalStorage="true"> Note: this must required if you'r targeting Android 10+

Solution 7:[7]

Starting from 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

Solution 8:[8]

Try this. Provide runtime permission for marshmallow it is perfectly work in my Application code :

 private String getFilename(String strFileName) {
        String filepath = Environment.getExternalStorageDirectory().getPath();
        File fileBase = new File(filepath, "Test");
        if (!fileBase.exists()) {
            fileBase.mkdirs();
        }
        return (file.getAbsolutePath() + "/" + strFileName + file_exts[currentFormat]);
    }

new File(getFilename(edt.getText().toString().trim()))

Solution 9:[9]

outputFile = new File(apkStorage + "/" + downloadFileName ); //Create Output file in Main File

            //Create New File if not present
            if (!outputFile.exists()) {
                isExternalStorageWritable();
                outputFile.getParentFile().mkdirs();
                outputFile.createNewFile();
                Log.e(TAG, "File Created");
                OutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
                InputStream fis = c.getInputStream();//Get InputStream for connection
                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                while ((len1 = fis.read(buffer)) >0) {
                    fos.write(buffer, 0, len1);//Write new file
                }

                //Close all connection after doing task
                fos.close();
                fis.close();

I wrote this code for creating a file, but it is not working in android 11

Solution 10:[10]

when writing code for android API 29 and above use the following permission in your application manifest (AndroidManifest.xml)

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

Adjust your code to read like the following

    ActivityCompat.requestPermissions(this, new String[]
                    {
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },
            PackageManager.PERMISSION_GRANTED);

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

    file = new File(Environment.getExternalStorageDirectory().getPath(), "TestDirectory/Document/");
    if (!file.exists()) {
        try {
            file.mkdirs();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

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
Solution 2 lallous34
Solution 3 mcatta
Solution 4 Ravi
Solution 5 Eaweb
Solution 6 AYUSH KUMAR SINGH
Solution 7
Solution 8 Mayur Patel
Solution 9 anuradha
Solution 10 Dharman