Java Files modification times
Read or set a file's last modification timestamp.
A simple example
Files modification times
- Start with A practice file and a chosen time
- Do this Set the modification time and read it back
- Result The chosen time, at filesystem precision
Syntax
public static FileTime getLastModifiedTime(Path path, LinkOption... options) throws IOException
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRebuild a dated newsletter archive
A volunteer restores the club newsletter from backup. The download time is today, but the archive sorts by the original publication time, so restore that timestamp before indexing the file.
import java.nio.file.*;
import java.nio.file.attribute.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path issue = Files.createFile(desk.resolve("newsletter.txt"));
var published = FileTime.fromMillis(1704067200000L);
Files.setLastModifiedTime(issue, published);
System.out.println(Files.getLastModifiedTime(issue).toInstant());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
2024-01-01T00:00:00Z
Printing the Instant uses UTC and gives the same time regardless of the computer's display timezone.
Compare two newsletter editions
An archive receives editions out of order during a restore. Give the two practice files known publication times and compare those times to decide which edition belongs first.
import java.nio.file.*;
import java.nio.file.attribute.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path first = Files.createFile(desk.resolve("winter"));
Path next = Files.createFile(desk.resolve("spring"));
Files.setLastModifiedTime(first, FileTime.fromMillis(1704067200000L));
Files.setLastModifiedTime(next, FileTime.fromMillis(1706745600000L));
System.out.println(Files.getLastModifiedTime(first).compareTo(Files.getLastModifiedTime(next)) < 0);
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true
Comparing FileTime values orders the editions without relying on directory iteration order.
Preserve a concert archive date
The school archives its concert program under the original performance date. After writing the export, set its modification time to noon UTC on the recorded day. Which date does the metadata report back?
What to watch for
Use a known timestamp for deterministic tests and compare only the precision your storage supports.