Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directory automatically on SD card

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?

like image 637
Kshitij Aggarwal Avatar asked Jan 25 '10 08:01

Kshitij Aggarwal


People also ask

How do you create a file on an SD card?

Use This: DocumentFile tempDir = DocumentFile. fromSingleUri(context,targetDirectoryUri); DocumentFile newDocumentFile = tempDir. createFile(type,name);


1 Answers

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" />
like image 176
Jeremy Logan Avatar answered Oct 01 '22 18:10

Jeremy Logan