snippetjavaCritical
How do I check if a file exists in Java?
Viewed 0 times
howjavacheckexistsfile
Problem
How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's
The only similar question on SO deals with writing the file and was thus answered using
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.
-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.
Solution
Using
java.io.File:File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}Code Snippets
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}Context
Stack Overflow Q#1816673, score: 1544
Revisions (0)
No revisions yet.