0

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!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kanagalingam
  • 2,096
  • 5
  • 23
  • 40

3 Answers3

1

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

GuyKhmel
  • 505
  • 5
  • 15
0

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;
}
Thomas Mary
  • 1,535
  • 1
  • 13
  • 24
0

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

Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34