Check if directory exist on android's sdcard - android

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

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.

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

The following code also works for java files:
// Create file upload directory if it doesn't exist
if (!sdcarddir.exists())
sdcarddir.mkdir();

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!!'
}

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

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

Related

mkdir return false in android?

This is my code
String DATA_PATH="/mnt/sdcard/";
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v("", "ERROR: Creation of directory " + path + " on sdcard failed");
} else {
Log.v("", "Created directory " + path + " on sdcard");
}
}
}
I've tried using Environment.getExternalDirectory() but it still return false. The most confusing thing is it always said "ERROR: Creation of directory mounted on sdcard failed" on the logcat. How can the path changed into mounted? Can someone please give me a solution?
if the mobile is connected to the system then we are not able to create folders so remove it and run the application
Why are you using mkdirs in the first place ? You should just do:
File file = new File(Environment.getExternalStorageDirectory(), "tessdata");
if (!file.exists()) file.mkdir();
Also, make sure you have the WRITE_EXTERNAL_STORAGE permission in the manifest.

android - file.exists() returns false for existing file (for anything different than pdf)

Both files are present on the sdcard, but for whatever reason exists() returns false the the png file.
//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";
File file2 = new File(path);
if (null != file2)
{
if(file2.exists())
{
LOG.x("file exist");
}
else
{
LOG.x("file does not exist");
}
}
Now, I've look at what's under the hood, what the method file.exists() does actually and this is what it does:
public boolean exists()
{
return doAccess(F_OK);
}
private boolean doAccess(int mode)
{
try
{
return Libcore.os.access(path, mode);
}
catch (ErrnoException errnoException)
{
return false;
}
}
May it be that the method finishes by throwing the exception and returning false?
If so,
how can I make this work
what other options to check if a file exists on the sdcard are available for use?
Thanks.
1 You need get the permission of device
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Get the external storage directory
File sdDir = Environment.getExternalStorageDirectory();
3 At last, check the file
File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
return false;
}
return true;
Note: filename is the path in the sdcard, not in root.
For example: you want find
/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
then filename is
./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
.
Please try this code. Hope it should helpful for you. I am using this code only. Its working fine for me to find the file is exists or not. Please try and let me know.
File file = new File(path);
if (!file.isFile()) {
Log.e("uploadFile", "Source File not exist :" + filePath);
}else{
Log.e("uploadFile","file exist");
}
Check that USB Storage is not connected to the PC. Since Android device is connected to the PC as storage the files are not available for the application and you get FALSE to File.Exists().
Check file exist in internal storage
Example : /storage/emulated/0/FOLDER_NAME/FILE_NAME.EXTENTION
check permission (write storage)
and check file exist or not
public static boolean isFilePresent(String fileName) {
return getFilePath(fileName).isFile();
}
get File from the file name
public static File getFilePath(String fileName){
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "FOLDER_NAME");
File filePath = new File(folder + "/" + fileName);
return filePath;
}

How to check for the existence of a file?

String extra=imagepath.get(i).toString();
String extra2=imageid.get(i).toString();
String path = "/mnt/sdcard/Android/data/com.example.webdata/files/Download/" + extra2 + ".jpg";
File f = new File(path);
if(f.exists())
{
//Toast.makeText(getApplicationContext(), "File already exists....",
// Toast.LENGTH_SHORT).show();
}
else
{
downloadfile();
}
I am using the above code to check if a file exists or not. I have checked it with one file and it works fine, but when I use it in my application where there are multiple (100-200) images it always starts downloading files whether they exist or not. Is there a better method than this?
First check how many images on folder:-
File extStore = Environment.getExternalStorageDirectory();
File[] imageDirs = extStore.listFiles(filterForImageFolders);
after above you run the loop and check u r condition:-
for(int i=0;i<list.length;i++)
{
// ur condition
}

file.mkdirs() not working

i want to write to a file in the sdcard of my phone.i used the below code to do this.
private CSVWriter _writer;
private File _directory;
public String _fileTestResult;
private String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
_writer=null;
_directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
if(!_directory.exists())
_directory.mkdirs();
}
public void exportResult(String testcaseNum,String testcase,String status){
try {
if(_directory.exists()){
//do something
}
but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.
note:i have given the permission in manifest file.
EDIT:
i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?
have you add the correct permission in your manifest ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit : ok, i just read your note for permission.
If it's help you this is my sdcard cache code :
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
String evtDir = "";
if(evt > 0){
evtDir = File.separator + evt;
}
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Android"
+ File.separator
+ "data"
+ File.separator
+ Application.getApplicationPackageName()
+ File.separator + "cache"
+ evtDir);
}else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
Try below code
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
imagefolder = new File(root,
mycontext.getString(R.string.app_name));
imagefolder.mkdirs();
}
} catch (Exception e) {
Log.e("DEBUG", "Could not write file " + e.getMessage());
}
Try with:
if(!_directory.exists())
_directory.mkdir();
Also check this - Creating a directory in /sdcard fails

How to create directory automatically on SD card

I'm trying to save my file to the following location
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/" it works.
Now I'm assuming that I'm not able to create directory automatically this way.
Can someone suggest how to create a directory and sub-directory using code?
If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is what works for me.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in your manifest and the code below
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Actually I used part of #fiXedd asnwer and it worked for me:
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it Image2.PNG
File file = new File(extStorageDirectory, "Image2.PNG");
Make sure that you are using mkdirs() not mkdir() to create the complete path
With API 8 and greater, the location of the SD card has changed. #fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).
You can read more in the SDK documentation.
Make sure external storage is present:
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
private boolean isExternalStoragePresent() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
.show();
}
return (mExternalStorageAvailable) && (mExternalStorageWriteable);
}
Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)
not allowed characters in file/folder names
" * / : < > ? \ |
U may find this code helpful in such a case.
The below code removes all ":" and replaces them with "-"
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
this will create a folder named dor in your sdcard.
then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and don't forget to add code in manifest
This will make folder in sdcard with Folder name you provide.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
ivmage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`

Categories

Resources