Java File type, size, and timestamps
Check whether an entry exists, identify its type, and inspect its size and modification time.
A simple example
File type, size, and timestamps
- Start with A regular file containing ASCII AB
- Do this Measure its length
- Result 2 bytes
Syntax
public boolean exists()
JDK 21 declarations (6)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck a daily sales export before mailing it
A shop emails a small sales report at closing time. Before attaching it, the clerk checks that the export exists as a regular file with the expected byte count and a recorded modification time.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File daily = Files.writeString(desk.resolve("daily.csv"), "tea").toFile();
System.out.println(daily.exists() && daily.isFile());
System.out.println(desk.toFile().isDirectory());
System.out.println(daily.length());
System.out.println(daily.lastModified() > 0);
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true 3 true
Three ASCII characters occupy three bytes in UTF-8. An existing directory is a different kind of entry.
Compare two hidden-file checks on a draft
A file browser needs to decide whether a draft belongs in its ordinary list. Compare the old and new Java APIs on the same temporary file without assuming that all systems use a leading dot as the hidden marker.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File draft = Files.createFile(desk.resolve("draft.txt")).toFile();
System.out.println(draft.isHidden() == Files.isHidden(draft.toPath()));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true
Both checks consult the local platform for this ordinary file.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
What to watch for
length and lastModified can return zero when a lookup fails. The meaning of hidden depends on the operating system.