Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?

The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.

If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.

like image 863
DVK Avatar asked Nov 29 '09 20:11

DVK


People also ask

How do you check file is exist or not?

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 exists in Java and delete it?

Files deleteIfExists() method in Java with Examples This method will return true if the file was deleted by this method; false if the file could not be deleted because it did not exist. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.


2 Answers

Using java.io.File:

File f = new File(filePathString); if(f.exists() && !f.isDirectory()) {      // do something } 
like image 139
Sean A.O. Harney Avatar answered Sep 20 '22 06:09

Sean A.O. Harney


I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile(); 

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

like image 34
Chris Dail Avatar answered Sep 19 '22 06:09

Chris Dail