Checking if a file or directory exists in Java

!Files.exists() returns:

  • true if the file does not exist or its existence cannot be determined
  • false if the file exists

Files.notExists() returns:

  • true if the file does not exist
  • false if the file exists or its existence cannot be determined

As we see from Files.exists the return result is:

TRUE if the file exists; 
FALSE if the file does not exist or its existence cannot be determined.

And from Files.notExists the return result is:

TRUE if the file does not exist; 
FALSE if the file exists or its existence cannot be determined

So if !Files.exists(path) return TRUE means it not exists or the existence cannot be determined (2 possibilities) and for Files.notExists(path) return TRUE means it not exists (just 1 possibility).

The conclusion !Files.exists(path) != Files.notExists(path) or 2 possibilities not equals to 1 possibility (see the explanation above about the possibilities).


Looking in the source code for the differences they both do the exact same thing with 1 major difference. The notExist(...) method has an extra exception to be caught.

Exist:

public static boolean exists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return true;
    } catch (IOException x) {
        // does not exist or unable to determine if file exists
        return false;
    }

}

Not Exist:

public static boolean notExists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return false;
    } catch (NoSuchFileException x) {
        // file confirmed not to exist
        return true;
    } catch (IOException x) {
        return false;
    }
}

As a result the differences are as follow:

  • !exists(...) returns the file as non existent if an IOException is thrown when attempting to retrieve the file.

  • notExists(...) returns the file as non existent by making sure the specific IOException subexception NoSuchFileFound is thrown and that it isn't any other subexception on IOException causing the not found result

Tags:

Java

File

Exists