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.

4/17/2020 6:08:00 PM

Accepted Answer


File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
9/7/2018 12:40:28 PM

By using nio in Java SE 7,

import java.nio.file.*;

Path path = Paths.get(filePathString);

if (Files.exists(path)) {
  // file exist

if (Files.notExists(path)) {
  // file is not exist

If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)

You can check if path is a directory or regular file.

if (Files.isDirectory(path)) {
  // path is directory

if (Files.isRegularFile(path)) {
  // path is regular file

Please check this Java SE 7 tutorial.


Using Java 8:

if(Files.exists(Paths.get(filePathString))) { 
    // do something

File f = new File(filePathString); 

This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:


So f.exists() can be used to check whether such a file exists or not.


f.isFile() && f.canRead()

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link