Sunday 5 November 2017

How do I check if a file exists in Java?

itemprop="text">

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



The only href="https://stackoverflow.com/questions/1237235/check-file-exists-java">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 text", but I can live with the
latter.



Answer




Using href="https://docs.oracle.com/javase/9/docs/api/java/io/File.html"
rel="noreferrer">java.io.File:




File
f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {

// do something
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...