user1342645
user1342645

Reputation: 655

Trying to check if a file exists in internal storage

The following code is how I am trying to identify if a file exists in the internal storage, MODE_PRIVATE.

public boolean isset(String filename){
    FileInputStream fos = null;
    try {
       fos = openFileInput(filename);
       //fos = openFileInput(getFilesDir()+"/"+filename);
       if (fos != null) {
         return true;
       }else{
         return false;
       }
    } catch (FileNotFoundException e) {
        return false;
    }

    //File file=new File(mContext.getFilesDir(),filename);

    //boolean exists = fos.exists();
    }

However, it goes into the exception and doesn't continue with the code. It doesn't do the return. Why?

Upvotes: 37

Views: 39892

Answers (3)

Shivam Tripathi
Shivam Tripathi

Reputation: 648

Kotlin: This works for me !!

fun check(path: String?): Boolean
{
    val file = File(path)
    return file.exists()
}

Upvotes: 2

Hassy31
Hassy31

Reputation: 2813

hope this method helps you.

public boolean fileExist(String fname){
    File file = getBaseContext().getFileStreamPath(fname);
    return file.exists();
}

Upvotes: 123

Nishanth
Nishanth

Reputation: 1871

For internal storage, this works for me:

public boolean isFilePresent(String fileName) {
    String path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName;
    File file = new File(path);
    return file.exists();
}

Upvotes: 13

Related Questions