How to create directory automatically on SD card
Asked Answered
C

13

194

I'm trying to save my file to the following location
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/" it works.

Now I'm assuming that I'm not able to create directory automatically this way.

Can someone suggest how to create a directory and sub-directory using code?

Corps answered 25/1, 2010 at 8:6 Comment(0)
A
456

If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:

// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);

Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.

UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Autonomic answered 25/1, 2010 at 8:33 Comment(9)
yes, the subsequently released Samsung tablets use built-in flashInterplanetary
don't forget to add to the AndroidManifest.xml the right to write https://mcmap.net/q/128101/-how-to-create-directory-automatically-on-sd-cardAdorno
It seams this is not working if I have an sub-sub folder, like /sdcard/com.my.code/data? How could I solve this?Spokesman
Besides creating this directory too? Is there a command like 'force' in unix mkdir?Spokesman
Works perfectly in api 19Ale
Does not work on on KitKat, external, physical sdcard.Stearns
You should probably use Environment.getExternalStorageDirectory().getPath()Sandbox
Creating a directory can fail, in which case .mkdirs() will return false. You should check the return value and react according, as noted e.g. in this answer to a similar question. A SecurityException is also possible.Oreste
When debugging your app on newer versions of Android, you have to also go to the permissions settings for the app and manually enable storage. Without that, the directory will not get created.Subulate
S
57

Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Stogy answered 14/12, 2010 at 3:52 Comment(0)
A
42

Here is what works for me.

 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

in your manifest and the code below

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}
Anabelanabella answered 16/9, 2011 at 2:4 Comment(2)
path is the name of the folder you wanna create. If you sent path like MusicDownload.. It automatically becomes /sdcard/MusicDownload. Shajeel AfzalCopolymer
It throws exception java.io.IOException: open failed: ENOENT (No such file or directory)Sisely
M
24

Actually I used part of @fiXedd asnwer and it worked for me:

  //Create Folder
  File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
  folder.mkdirs();

  //Save the path as a string value
  String extStorageDirectory = folder.toString();

  //Create New file and name it Image2.PNG
  File file = new File(extStorageDirectory, "Image2.PNG");

Make sure that you are using mkdirs() not mkdir() to create the complete path

Manlike answered 3/4, 2012 at 9:17 Comment(2)
How is this "part" of @fixedd answer? His answer was to use File.mkdirs(). He then showed an example of using it.Pinafore
Actually I can't remember what was the difference but I think there were some edits ... By the way I mentioned that I used his answer to get the solutionManlike
F
12

With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).

You can read more in the SDK documentation.

Flinger answered 1/3, 2011 at 15:36 Comment(0)
T
8

Make sure external storage is present: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

private boolean isExternalStoragePresent() {

        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but
            // all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
            Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
                    .show();

        }
        return (mExternalStorageAvailable) && (mExternalStorageWriteable);
    }
Talia answered 29/2, 2012 at 10:18 Comment(0)
F
6

Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)

not allowed characters in file/folder names

" * / : < > ? \ |

U may find this code helpful in such a case.

The below code removes all ":" and replaces them with "-"

//actualFileName = "qwerty:asdfg:zxcvb" say...

    String[] tempFileNames;
    String tempFileName ="";
    String delimiter = ":";
    tempFileNames = actualFileName.split(delimiter);
    tempFileName = tempFileNames[0];
    for (int j = 1; j < tempFileNames.length; j++){
        tempFileName = tempFileName+" - "+tempFileNames[j];
    }
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
    if (!file.exists()) {
        if (!file.mkdirs()) {
        Log.e("TravellerLog :: ", "Problem creating Image folder");
        }
    }
Forbidden answered 25/6, 2012 at 18:28 Comment(1)
+1 ya i too tried with : and got error and finally found that issue and removed : and all other special chars.Millennium
S
6
     //Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}


File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
Single answered 14/8, 2014 at 9:7 Comment(0)
C
5

I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
Crescent answered 17/2, 2012 at 15:48 Comment(0)
N
5
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();

this will create a folder named dor in your sdcard. then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:

 File file1 = new File(sdcard,"/dor/fitness.json");
 .......
 .....

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

and don't forget to add code in manifest

Nona answered 9/6, 2014 at 10:45 Comment(0)
D
5

This will make folder in sdcard with Folder name you provide.

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
        if (!file.exists()) {
            file.mkdirs();
        }
Duncandunce answered 2/12, 2016 at 6:3 Comment(0)
B
3

Just completing the Vijay's post...


Manifest

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

Function

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}

Usage

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt

You could check for errors

if(createDirIfNotExists("mydir/")){
     //Directory Created Success
}
else{
    //Error
}
Bristletail answered 28/10, 2014 at 12:19 Comment(0)
T
1
ivmage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);

        }
    });`
Tome answered 19/2, 2016 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.