Course contentsShow
← Java
Lesson 2065 of 2,87041. NIO.2 and the Path APIFree lesson

Files.exists() and Files.notExists()

Check if a file or directory exists using Path objects and understand the difference between these two methods.

Files.exists() and Files.notExists()

You'll learn how to check whether a file or directory exists using NIO.2's Path-based methods and understand the subtle but important differences between them.

The Core Idea

When working with files, you often need to verify their existence before performing operations. NIO.2 provides two methods in the Files utility class:

  • Files.exists(Path path) - returns true if the file exists
  • Files.notExists(Path path) - returns true if the file definitely does not exist

Think of these like asking two different questions: "Is this definitely here?" versus "Is this definitely not here?" The difference matters when the answer is uncertain.

Why Two Methods?

Here's the subtle but crucial distinction: these methods are NOT logical opposites.

If Files.exists() returns false, it could mean:

  1. The file doesn't exist, OR
  2. The file's existence cannot be determined (permissions issue, I/O error, etc.)

Files.notExists() only returns true when it can confirm the file is absent. If existence is uncertain, it returns false.

Basic Usage

Path path = Paths.get("myfile.txt");

if (Files.exists(path)) {
    System.out.println("File exists");
}

if (Files.notExists(path)) {
    System.out.println("File definitely does not exist");
}

// Both can be false simultaneously!
if (!Files.exists(path) && !Files.notExists(path)) {
    System.out.println("Cannot determine if file exists");
}

This three-state logic (exists, doesn't exist, unknown) makes file operations more robust when dealing with permission issues or network filesystems.

Key Takeaway: Use Files.exists() to check if a file is present, and Files.notExists() when you need to confirm absence. Remember: they're not simply !exists() — both can return false when the file's existence is indeterminate.