In Java, Files.exists(path) returns true when a file, folder, or other entry exists at path, and false otherwise. It never throws IOException.
false means "does not exist or could not be checked", for example because of missing permissions. That is why exists and notExists are not exact opposites: both can be false.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.exists(...), after import java.nio.file.Files;. You never create a Files object.
Syntax
Pass a path and, optionally, LinkOption.NOFOLLOW_LINKS:
Java
boolean there = Files.exists(dir.resolve("todo.txt"));
boolean linkItself = Files.exists(link, LinkOption.NOFOLLOW_LINKS);
Call
What it does
Files.exists(p)
Follows symbolic links: is the final target there?
Files.exists(p, NOFOLLOW_LINKS)
Is the entry itself there, even a dangling link?
Files.notExists(p)
true only when absence is confirmed.
Since Java 7. The answer is only a snapshot: another program can create or delete the file right after the check. When you are about to act, prefer calls that fail clearly, such as createFile or deleteIfExists.
Library declarations
Java
public static boolean exists(Path path, LinkOption... options)
Parameters
Parameter
Description
path
The path to test.
options
LinkOption.NOFOLLOW_LINKS to test a symbolic link itself.
Return Value
Return Value
Description
true
The entry exists.
false
It does not exist, or its existence could not be determined.
Run with java ExistsDefaultConfig. The output is the same on Windows, macOS, and Linux.
Created default config
Run 1: volume=5
Run 2: volume=9
How It Works
First run. app.cfg is missing, so the helper writes volume=5 and prints a note; that note appears before "Run 1" because loadConfig runs before println can print its line.
The user edits it. The program then stores volume=9, as a user changing a setting would.
Second run keeps it. Now exists is true, the default is skipped, and the user's value is returned. Two programs starting at the same moment could still race here; createFile closes that gap.
Example 3 — Test Files, Folders, and Impossible Paths
Check four names in a loop, including one that tries to go through a regular file as if it were a folder.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExistsSeveral {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path todo = Files.createFile(dir.resolve("todo.txt"));
Path photos = Files.createDirectory(dir.resolve("photos"));
String[] names = {"todo.txt", "photos", "missing.txt", "todo.txt/child"};
for (String n : names) {
System.out.println(n + " -> " + Files.exists(dir.resolve(n)));
}
Files.delete(todo);
Files.delete(photos);
Files.delete(dir);
}
}
Output
Run with java ExistsSeveral. The output is the same on Windows, macOS, and Linux.