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/mkyong/file.txt");
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.
package com.mkyong.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 GetLastModifiedTime1 {
public static void main(String[] args) {
String fileName = "/home/mkyong/file.txt";
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: 2020-07-20T09:29:54.627222Z
lastAccessTime: 2020-07-21T12:15:56.699971Z
lastModifiedTime: 2020-07-20T09:29:54.627222Z
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](https://en.wikipedia.org/wiki/Epoch_(computing). We can use SimpleDateFormat to make it a more human-readable format.
package com.mkyong.io.howto;
import java.io.File;
import java.text.SimpleDateFormat;
public class GetLastModifiedTime2 {
public static void main(String[] args) {
String fileName = "/home/mkyong/test";
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 : 1595237394627
After Format : 07/20/2020 17:29:54
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Thank you! 🙂
Hi MKyoung, I need to download the latest file from SFTP server but i don’t want to give the filename. It has to downloaded based on the last modified timestamp from server.
Thanks.
Muito bom, obrigado.
Thanks, good!
thanks its very usefull !!