In Java, we can use Files.readAttributes() to get the file metadata or attribute, and then lastModifiedTime() to display the last modified date of a file.
Path file = Paths.get("/home/tvt/workspace/favtuts/sample.csv");
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
1. BasicFileAttributes (NIO)
This example uses the java.nio.* to display the file attributes or metadata – creation time, last access time, and last modified time.
GetLastModifiedTime.java
package com.favtuts.io.howto;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class GetLastModifiedTime {
public static void main(String[] args) {
String fileName = "/home/tvt/workspace/favtuts/sample.csv";
try {
Path file = Paths.get(fileName);
BasicFileAttributes attr =
Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
creationTime: 2022-05-08T16:56:58.214937Z
lastAccessTime: 2022-05-08T17:24:20.346167Z
lastModifiedTime: 2022-05-08T16:56:58.214937Z
The BasicFileAttributes also works for the directory, and we can use the same code to display the last modified time of a directory.
Further Reading
Read this example to convert the FileTime to another date-time format.
2. File.lastModified (Legacy IO)
For legacy IO, we can use the File.lastModified() to get the last modified time; the method returns a long value measured in milliseconds since the epoch time. We can use SimpleDateFormat to make it a more human-readable format.
GetLastModifiedTime.java
package com.favtuts.io.howto;
import java.io.File;
import java.text.SimpleDateFormat;
public class GetLastModifiedTime {
public static void main(String[] args) {
String fileName = "/home/tvt/workspace/favtuts/sample.csv";
File file = new File(fileName);
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("After Format : " + sdf.format(file.lastModified()));
}
}
Output
Before format : 1652029018214
After Format : 05/08/2022 23:56:58
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io