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)- returnstrueif the file existsFiles.notExists(Path path)- returnstrueif 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:
- The file doesn't exist, OR
- 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.