Check if directory exist on android's sdcard
91,656
Solution 1
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.
Solution 2
File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
// do something here
}
Solution 3
The following code also works for java files:
// Create file upload directory if it doesn't exist
if (!sdcarddir.exists())
sdcarddir.mkdir();
Solution 4
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!!'
}
Author by
Alxandr
I'm a smalltimeprogrammer currently studying at NTNU-Norway.
Updated on March 02, 2020Comments
-
Alxandr over 4 years
How do I check if a directory exist on the sdcard in android?
-
Alxandr about 14 yearsMy error just turned out to be a lacking directory in my path, but thanks. I began to wonder if android's filesystem didn't support normal methods like this :-P
-
Chrispix about 12 yearsJust a note, getExternalStorageDirectory() May not actually point to the physical sd_card, it could point to internal storage. developer.android.com/reference/android/os/…
-
Yash almost 11 yearsChrispix, your comment is misleading. getExternalStorageDirectory() will point to the storage which shares data across all applications. This could be the SD Card, and for devices without SD Cards it points to the reserved storage area that is used as external storage. Internal storage is where private data (to the application - usually data/data) is stored.
-
Luis A. Florit almost 11 yearsThis doesn't work for me, since getExternalStorageDirectory() it returns the internal storage.
-
ABS about 10 yearsThere is no "isReadable" method! Unfortunately only a "setReadable" method is available, not even "getReadable"!!! So how we can get this value?!
-
Muhammad Babar over 9 years
Might also want to check f.exists(), because if it exists, and isDirectory() returns false, you'll have a problem
? can you please elaborate? why wouldisDirectory()
returns false when it actually exists? -
synic over 9 years@muhammad: it might exist and just be a file, instead of a directory.
-
Mann over 8 yearsIs it necessary to check both if
exists()
andisDirectory()
? I mean what if we use any one of them ?