Reputation: 14771
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
Reputation: 159
File file = new File(Environment.getExternalStorageDirectory() + "/filename");
if(file.exists){
return true;
}else{
return false;
}
Upvotes: -1
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
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
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
Reputation: 43
Try this:
File file = getContext().getFileStreamPath(file_name);
if(file.exists()){
FileInputStream fileIn= new FileInputStream(file);
...
}
Upvotes: 0