简体   繁体   中英

To create a directory in Sd card inside an application

I want to create a directory on sd card keeping it as a separate activity in one of my application. I wrote the following code in the onCreate() of the application. It is not creating the directory though this code works fine if I try to implement it as an independent application. Please suggest a solution for this problem.

  public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{ 
            String dirName = "/sdcard/TEST"; 
            File newFile = new File(dirName); 
            newFile.mkdirs(); 
            Log.d("CaptureTest.java","Directory created");
            if(newFile.exists()){ 
                Log.d("capturetest.java","directory exists"); 
                if(newFile.isDirectory()){ 
                    Log.d("capturetest.java","isDirectory = true"); 
                }
                else Log.d("capturetest.java","isDirectory = false"); 
            } else
                 { 
                Log.d("capturetest.java","directory doesn't exist"); 
            } 


        } catch(Exception e){ 


            Log.d("capturetest.java","Exception creating folder " + e); 


        }  


........................................
..........................................

}

The SD card might be mounted at /mnt/sdcard instead of /sdcard . But the safest technique to get the external storage directory is like in the following code

File myDirectory = new File(Environment.getExternalStorageDirectory(), "my directory");
if(!myDirectory.exists()) {
    myDirectory.mkdirs();
}

There could be a number of things causing this:

  1. Check that external storage is available and writeable before trying to write to it.
  2. Don't use String dirName = "/sdcard/TEST"; use Environment.getExternalStorageDirectory() or Context.getExternalFilesDir() instead.

This page has some really useful tips for correctly accessing the SD card.

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