Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to check if a file exists in internal storage

Tags:

java

android

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?

like image 835
user1342645 Avatar asked May 14 '12 02:05

user1342645


People also ask

How do you check file is exist or not?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

Which method is used to check file existence?

The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.

How do you check if a file already exist in C?

access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.


2 Answers

hope this method helps you.

public boolean fileExist(String fname){     File file = getBaseContext().getFileStreamPath(fname);     return file.exists(); } 
like image 126
Hassy31 Avatar answered Oct 08 '22 13:10

Hassy31


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(); } 
like image 45
Nishanth Avatar answered Oct 08 '22 13:10

Nishanth