Check if directory exist on android's sdcard

前端 未结 6 692
时光说笑
时光说笑 2020-12-24 05:01

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

相关标签:
6条回答
  • 2020-12-24 05:11
    File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
    if(dir.exists() && dir.isDirectory()) {
        // do something here
    }
    
    0 讨论(0)
  • 2020-12-24 05:21

    The following code also works for java files:

    // Create file upload directory if it doesn't exist    
    if (!sdcarddir.exists())
       sdcarddir.mkdir();
    
    0 讨论(0)
  • 2020-12-24 05:25

    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();
                    }

    0 讨论(0)
  • 2020-12-24 05:27

    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.

    0 讨论(0)
  • 2020-12-24 05:28

    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().

    0 讨论(0)
  • 2020-12-24 05:29

    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!!'
    }
    
    0 讨论(0)
提交回复
热议问题