Wednesday, November 20, 2013

Folder in SD Card's Root Directory

If you check out the files in your phone, you'll see several folders in the root directory. Usually you have a Downloads folder, a Music folder, and sometimes, there are custom folders created by your apps. How can you do this? Here are some steps to make a folder and to put a txt file in it.

1.) Create a File object for the directory:
exampleDirectory = new File("/sdcard/foldername/"); 
2.) Make that File object build the directory structure with the built in mkdrs() method:
example Directory.mkdirs();
 
3.) Create a File object for the output file, and attach the OutputStream to the file. You have to put this in a try and catch method to make Android happy:
File outputFile = new File(exampleDirectory, astringorfileyoucreated+".txt");        
            try {
                FileOutputStream fos = new FileOutputStream(outputFile);           
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

4.)  Add these permissions to your manifest:
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
       <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


That is all there is to it. Try it and check out that nice new folder in your root directory.

No comments:

Post a Comment