Files.exists()
Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().
Available since: Java 7
Syntax
static boolean exists(Path path, LinkOption... options)Parameters
| Parameter | Type | Description |
|---|---|---|
| path | Path | The path to check. |
| options | LinkOption... | NOFOLLOW_LINKS — do not follow symbolic links. Usually omitted. |
Return value
booleantrue if the file or folder exists.
Examples
Checks before and after creating a file:
void main() throws IOException {
Path file = Path.of("config.txt");
IO.println(Files.exists(file));
Files.writeString(file, "debug=true");
IO.println(Files.exists(file));
IO.println(Files.isDirectory(file));
IO.println(Files.size(file));
Files.delete(file);
}Output:
false
true
false
10Notes
The file can appear or disappear between the check and the action, so the check does not replace handling IOException. It is often simpler to just do the action and catch the exception, or use Files.deleteIfExists().
See also
- Files.delete() — Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
- Files.createDirectories() — Creates a folder together with all missing parent folders.
- Path.of() — Creates a Path object — a path to a file or folder.
Related recipes
In the tutorial
- Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.