Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (1.1k points)

How can I check whether a file exists, before opening it for reading in Java? (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 text", but I can live with the latter.

1 Answer

0 votes
by (13.2k points)

You can use the method for this.It tests the existence of the file or directory.

If the file defined by the abstract pathname exists, then this method returns boolean true, otherwise it returns boolean false.This method doesn’t throw any exception.

File f = new File(filePathString);

if(f.exists() && !f.isDirectory()) { 

    // do something


Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Aditya98 (1.3k points)
0 votes
1 answer
asked Jul 10, 2019 in Java by tara92 (920 points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories