Files.getLastModifiedTime() and File Timestamps
What you'll learn: How to retrieve when a file was last modified using Files.getLastModifiedTime() and understand the precision of file timestamps.
Understanding File Timestamps
Every file system tracks metadata about files, including when they were last modified. In Java's NIO.2 API, you can access this information using Files.getLastModifiedTime(), which returns a FileTime object representing the timestamp.
Think of FileTime like a high-precision clock reading frozen at the exact moment the file was last changed. Unlike the old File.lastModified() method that returned milliseconds as a long, FileTime provides a more sophisticated representation with better resolution.
Using Files.getLastModifiedTime()
Path path = Paths.get("data.txt");
FileTime lastModified = Files.getLastModifiedTime(path);
System.out.println("Last modified: " + lastModified);
// Output: Last modified: 2024-01-15T14:30:45.123456Z
The method throws IOException if the file doesn't exist or can't be read, so you'll need proper exception handling.
Understanding Timestamp Resolution
File systems vary in their timestamp precision:
- NTFS (Windows): 100-nanosecond resolution
- ext4 (Linux): 1-nanosecond resolution
- FAT32: 2-second resolution (very coarse!)
FileTime preserves this precision but doesn't guarantee what you'll actually get—it depends on the underlying file system.
FileTime time = Files.getLastModifiedTime(path);
long millis = time.toMillis();
Instant instant = time.toInstant();
You can convert FileTime to milliseconds or an Instant for comparison or formatting purposes.
Key Takeaway: Files.getLastModifiedTime() returns a FileTime object representing when a file was last modified, with precision that depends on the underlying file system—use it for reliable timestamp access in modern Java applications.