Sub topic 11
Checking existence and reading attributes
This chapter assumes you can build a Path with Path.of, call static methods on Files, and handle IOException with try/catch. Here you learn how to ask the file system about a path without reading its contents: whether it exists, what kind of thing it is, how big it is, and when it changed.
Existence checks are a three-way answer
Files.exists(path) and Files.notExists(path) look like opposites, but they are not. Each returns true only when it can prove its answer. If the JVM cannot tell, for example because a parent directory is unreadable, both return false.
| Situation | `exists` | `notExists` |
|---|---|---|
| The file is present | `true` | `false` |
| The file is absent | `false` | `true` |
| Status cannot be determined | `false` | `false` |
Use exists when you want to proceed only on a confirmed hit. Use notExists when you want to proceed only on a confirmed miss, such as before creating something. Avoid !Files.exists(p) as a stand-in for "definitely missing", because it is also true in the unknown case.
Asking what kind of thing a path is
A path can name a regular file, a directory, a symbolic link, or something else, such as a device. The Files class has a boolean method for each question.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExistenceDemo {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("meta");
Path file = dir.resolve("notes.txt");
Files.writeString(file, "hello\n");
Path missing = dir.resolve("missing.txt");
System.out.println("exists(file): " + Files.exists(file));
System.out.println("exists(missing): " + Files.exists(missing));
System.out.println("notExists(missing): " + Files.notExists(missing));
System.out.println("isRegularFile(file): " + Files.isRegularFile(file));
System.out.println("isDirectory(file): " + Files.isDirectory(file));
System.out.println("isDirectory(dir): " + Files.isDirectory(dir));
System.out.println("isReadable(file): " + Files.isReadable(file));
System.out.println("isWritable(file): " + Files.isWritable(file));
System.out.println("isSameFile: " + Files.isSameFile(file, dir.resolve("./notes.txt")));
Files.delete(file);
Files.delete(dir);
}
}The program prints true, false, true, true, false, true, true, true, true, one per line, each after its label. Files.isSameFile compares the actual files, so two different spellings of one location count as the same.
Other useful checks are Files.isExecutable, Files.isHidden, and Files.isSymbolicLink. isHidden depends on the platform: a leading dot on Unix-like systems, a hidden flag on Windows.
Every is... method returns false for a missing path. Files.isDirectory(p) being false therefore does not mean "p is a file". It may mean "p does not exist".
Symbolic links
By default these methods follow symbolic links. If link points to a missing target, Files.exists(link) is false even though the link itself is there. Pass LinkOption.NOFOLLOW_LINKS to test the link itself:
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
public class LinkCheck {
public static void main(String[] args) {
Path p = Path.of("maybe-a-link");
boolean linkItself = Files.exists(p, LinkOption.NOFOLLOW_LINKS);
boolean target = Files.exists(p);
System.out.println(linkItself + " " + target);
}
}A dangling link prints true false. When no such path exists, it prints false false.
Check-then-act is a race
A common pattern looks safe but is not:
if (Files.exists(path)) {
String text = Files.readString(path); // may still throw
}Between the check and the read, another process can delete the file. The answer from exists is only a snapshot. This gap is known as a time-of-check to time-of-use (TOCTOU) race.
The reliable approach is to attempt the operation and handle the exception. You saw NoSuchFileException in the error-handling chapter. Reserve existence checks for decisions that are not safety-critical, such as choosing a default or printing a friendlier message.
Reading basic attributes
Several one-value methods exist: Files.size(path) returns the size in bytes as a long, and Files.getLastModifiedTime(path) returns a FileTime. Unlike the boolean checks, these throw NoSuchFileException if the path is missing.
When you need more than one value, read them together with Files.readAttributes. It asks the file system once and returns an immutable snapshot, so the values are consistent with each other.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
public class AttributesDemo {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("attrs", ".txt");
Files.writeString(file, "hello\n");
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("size: " + attrs.size());
System.out.println("regular: " + attrs.isRegularFile());
System.out.println("directory: " + attrs.isDirectory());
System.out.println("symlink: " + attrs.isSymbolicLink());
System.out.println("modified: " + attrs.lastModifiedTime());
Files.setLastModifiedTime(file, FileTime.from(Instant.parse("2024-01-01T00:00:00Z")));
System.out.println("after set: " + Files.getLastModifiedTime(file));
Files.delete(file);
}
}The size is 6, because hello\n is six bytes in UTF-8. The last line prints 2024-01-01T00:00:00Z. The first modified time depends on when you run the program.
BasicFileAttributes also offers creationTime(), lastAccessTime(), isOther(), and fileKey(). Keep these limits in mind:
FileTimeconverts toInstantwithtoInstant(). It has no time zone, so format it yourself if you show it to people.- Some file systems do not record creation time, and others report a value equal to the modification time.
- The size of a directory is unspecified. Do not use it to count entries.
- Last-access time is often disabled or coarse for performance reasons.
By default readAttributes follows symbolic links. Pass LinkOption.NOFOLLOW_LINKS as a final argument to describe the link itself.
Platform-specific attribute views
The basic view works everywhere. Richer data lives in optional views that a given file system may or may not support. On Unix-like systems you can read owner and permissions with PosixFileAttributes. On other systems the call throws UnsupportedOperationException, so a portable program catches it.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
public class PosixDemo {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("posix", ".txt");
try {
PosixFileAttributes attrs = Files.readAttributes(file, PosixFileAttributes.class);
System.out.println(PosixFilePermissions.toString(attrs.permissions()));
System.out.println(attrs.owner().getName());
} catch (UnsupportedOperationException e) {
System.out.println("POSIX attributes not supported here");
} finally {
Files.delete(file);
}
}
}On Linux or macOS, a file made by createTempFile is typically rw-------, which means only the owner can read and write it. The owner name is your user account.
You can ask which views a file system supports with FileSystems.getDefault().supportedFileAttributeViews(). The result is a set of names such as basic, posix, unix, dos, and owner.
Choosing the right call
- Use
Files.existsorFiles.notExistsonly for hints, never as a guarantee. - Use the exception from the real operation to detect a missing file.
- Use
Files.readAttributeswhen you need two or more attributes. - Use
Files.sizewhen you need only the size, for example to warn before loading a large file withFiles.readString. - Catch
UnsupportedOperationExceptionaround optional views.
Exercise
A colleague writes if (!Files.exists(config)) { createDefaultConfig(); }. On a server, a permissions problem makes the parent directory unreadable. What goes wrong, and what is a better test?
Show answer
When the parent directory is unreadable, the file system cannot say whether the file exists, so Files.exists returns false. The negation is then true, and the code overwrites or tries to create a config that may already be there. Use Files.notExists(config), which is false in the unknown case, so the default is created only when absence is confirmed. Better still, create it with Files.writeString(config, defaults, StandardOpenOption.CREATE_NEW) and catch FileAlreadyExistsException, which removes the race between check and creation.
Exercise
Why is Files.readAttributes(path, BasicFileAttributes.class) preferred over calling Files.size, Files.isDirectory, and Files.getLastModifiedTime separately when you need all three?
Show answer
It queries the file system once and returns an immutable snapshot, so the three values are consistent with each other. Separate calls make three queries, and the file can change between them. It is also fewer calls.