Reputation: 2184
I have been working on a project where I will get a filename from API and have to check whether the file is present in the device and play it.
I am getting Screenshot.jpg
as filename from API and under the same name a file is present in my storage.
But when I used the piece of code, I have been returned false. I have checked with other codes also.
public boolean isFilePresent(String fileName) {
String path = this.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
where am I going wrong? Any help would be greatly appreciated!
Upvotes: 0
Views: 999
Reputation: 2668
Use Environment.getExternalStorageDirectory()
this is how you get the files directory
then you will add your files path after it, so you should do something like this
if(!new File(Environment.getExternalStorageDirectory().toString()+"/myFolder/"+"myFile").exist())
{
// file is not exist
}
remember to check the runtime permission because it's a special permission
Upvotes: 0
Reputation: 505
Probably, what you do wrong is using this.getFilesDir()
.
Instead, use Environment.getExternalStorageDirectory().toString()
for example, it's all dependant on where your file is.
Like I said before, debug it yourself, print (or present a toast) with the 'expected' file path, then verify it doesn't exist
Upvotes: 1
Reputation: 1579
Try something like that :
public boolean isFilePresent(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File[] filesArray = dirFiles.listFiles();
for (File file : filesArray) {
if (file.getName().equals(fileName)) {
return true;
}
}
return false;
}
Upvotes: 0