Java File.setLastModified
Set the last modification time using milliseconds since the Unix epoch.
A simple example
File.setLastModified
- 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 boolean setLastModified(long time)
JDK 21 declarations (1)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPreserve an invoice date during an import
An office is moving old invoices into a new archive. Their original modification dates determine the order of a monthly report, so the importer restores a whole-second timestamp after creating the new file.
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 invoice = Files.createFile(desk.resolve("invoice.csv")).toFile();
long millis = 1704067200000L;
System.out.println(invoice.setLastModified(millis));
System.out.println(invoice.lastModified() / 1000 == millis / 1000);
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true
The comparison checks seconds so finer timestamp precision is unnecessary.
Report a missing archived receipt
A migration log lists one receipt that was never copied. Attempt to restore its timestamp and check the status before marking that receipt as successfully imported.
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 missing = new File(desk.toFile(), "missing.csv");
System.out.println(missing.setLastModified(1704067200000L));
System.out.println(missing.exists());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
false false
Setting the timestamp fails and does not create a substitute receipt.
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
Filesystem timestamp precision varies. Read the value back at the resolution that the application actually needs.