Wai Yan Hein
Wai Yan Hein

Reputation: 14771

Checking file exists or not in android is not working

I am developing an Android app. I am still learning android. But I am having a problem with checking file in download folder exists or not. It is always returning false. But the file actually exists.

This is the function to check file exists or not in CommonHelper class

    public static boolean fileExists(String path)
    {
        File file = new File(path);
        if(file.exists())
        {
            return true;
        }
        else{
            return false;
        }
    }

This is how I am checking files in built in download folder

   if(CommonHelper.fileExists(String.valueOf(Environment.DIRECTORY_DOWNLOADS)+"/"+cursor.getString(1)))
   {
         //do other stuffs here
   }

What is wrong with my code?

Upvotes: 0

Views: 3144

Answers (5)

AnanduKrishnan P.S.
AnanduKrishnan P.S.

Reputation: 159

File file = new File(Environment.getExternalStorageDirectory() + "/filename");

if(file.exists){
    return true;
}else{
return false;
}

Upvotes: -1

Anup Dasari
Anup Dasari

Reputation: 488

try this

 if(CommonHelper.fileExists(new File(Environment.DIRECTORY_DOWNLOADS),cursor.getString(1)))
{
     //do other stuffs here
}

and

 public static boolean fileExists(File directory, String fileName)
{
    File file = new File(directory,fileName);
    if(file.exists())
    {
        return true;
    }
    else{
        return false;
    }
}

Upvotes: 0

AlbAtNf
AlbAtNf

Reputation: 3909

The problem is, that you are not getting the full path.

Try getting the path with Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

public static boolean fileExists(File path, String filename){
        return new File(path, filename).exists();
}

And then call:

CommonHelper.fileExists(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), cursor.getString(1));

EDIT: Please note, getExternalStoragePublicDirectory can also be something else, like getExternalStorageDirectory() depending, on where you actually stored your file.

Upvotes: 2

Rishad Appat
Rishad Appat

Reputation: 1806

you have to add the file name to the path when creating the file... Please try as below..

File file = new File(storagePath + "/" + fileName);
if (file.exists()) {
   return true;
}
else
{
 return false;
}

Upvotes: 0

Dani Costa
Dani Costa

Reputation: 43

Try this:

    File file = getContext().getFileStreamPath(file_name);       
   if(file.exists()){

    FileInputStream fileIn= new FileInputStream(file);
     ...
    }

Upvotes: 0

Related Questions