Java NIO and java.time
While the old File
class does offer what we need here, I always use the more modern Java NIO (New IO, since Java 1.7) package for file operations. It offers many more operations, so just to make my code ready for any future requirements that File
may not support. In some situations it is also nicer to work with, for example it provides some support for stream operations (since Java 1.8, obviously).
I very definitely recommend that you use java.time, the modern Java date and time API, for your date and time work.
The two recommendations go nicely hand in hand since a java.nio.file.attribute.FileTime
has a toInstant
method for converting to a java.time.Instant
.
To find the file that was least recently modified (where its last modification is the longest time ago):
Path dp = Paths.get("/path/to/your/dir");
Optional<Path> firstModified = Files.list(dp)
.min(Comparator.comparing(f -> getLastModified(f)));
firstModified.ifPresentOrElse(
p -> System.out.println("" + p + " modified "
+ getLastModified(p).atZone(ZoneId.systemDefault())
.format(FORMATTER)),
() -> System.out.println("No files"));
Example output:
./useCount.txt modified 2016-12-26 15:11:54
The code uses this auxiliary method:
private static Instant getLastModified(Path p) {
try {
return Files.readAttributes(p, BasicFileAttributes.class).lastModifiedTime().toInstant();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
— and this formatter:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
For the creation time instead of the last modification time use creationTime()
in this line;
return Files.readAttributes(p, BasicFileAttributes.class).creationTime().toInstant();
For the file that has been modified last just use max()
instead of min()
in this line:
.max(Comparator.comparing(f -> getLastModified(f)));
./bin modified 2021-10-12 07:57:08
By the way directory.lastModified()
used in your question gives you the last time the directory itself was modified. It is (usually) not the same time the last file in the directory was modified.
Tutorial links