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.
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.
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.
Using java.io.File
:
File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With