Alxandr
Alxandr

Reputation: 12423

Check if directory exist on android's sdcard

How do I check if a directory exist on the sdcard in android?

Upvotes: 65

Views: 97113

Answers (6)

synic
synic

Reputation: 26668

Regular Java file IO:

File f = new File(Environment.getExternalStorageDirectory() + "/somedir");
if(f.isDirectory()) {
   ....

Might also want to check f.exists(), because if it exists, and isDirectory() returns false, you'll have a problem. There's also isReadable()...

Check here for more methods you might find useful.

Upvotes: 134

Agilarasan anbu
Agilarasan anbu

Reputation: 2805

Yup tried a lot, beneath code helps me :)

 File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "ur directory name");

                if (!folder.exists()) {
                    Log.e("Not Found Dir", "Not Found Dir  ");
                } else {
                    Log.e("Found Dir", "Found Dir  " );
                   Toast.makeText(getApplicationContext(),"Directory is already exist" ,Toast.LENGTH_SHORT).show();
                }

Upvotes: 0

user942821
user942821

Reputation:

I've made my mistake about checking file/ directory. Indeed, you just need to call isFile() or isDirectory(). Here is the docs

You don't need to call exists() if you ever call isFile() or isDirectory().

Upvotes: 1

Ingo
Ingo

Reputation: 5381

General use this function for checking is a Dir exists:

public boolean dir_exists(String dir_path)
  {
    boolean ret = false;
    File dir = new File(dir_path);
    if(dir.exists() && dir.isDirectory())
      ret = true;
    return ret;
  }

Use the Function like:

String dir_path = Environment.getExternalStorageDirectory() + "//mydirectory//";

if (!dir_exists(dir_path)){
  File directory = new File(dir_path); 
  directory.mkdirs(); 
}

if (dir_exists(dir_path)){
  // 'Dir exists'
}else{
// Display Errormessage 'Dir could not creat!!'
}

Upvotes: 2

Artail3
Artail3

Reputation: 272

The following code also works for java files:

// Create file upload directory if it doesn't exist    
if (!sdcarddir.exists())
   sdcarddir.mkdir();

Upvotes: 17

Mark B
Mark B

Reputation: 200501

File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
    // do something here
}

Upvotes: 47

Related Questions