简体   繁体   中英

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

For those not as experienced like me. I fought this issue, lost hair for some time. I am targeting api 21 (for compatibility sake) and it worked on lollipop but on marshmallow it would not create the directory. I did have the "uses" permission in the manifest but it still would not work. Apparently in Marshmallow when you install with Android studio it never asks you if you should give it permission it just quietly fails, like you denied it. You must go into Settings, apps, select your application and flip the permission switch on.

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.

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.

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

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

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

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.

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+

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()))

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM