There are two ways to get the last modified date of a file in Java.
- Using File.lastModified() method- Using this method you can get the file's last modified timestamp.
- Using Files.readAttributes() method- Java 7 onward you can use Files.readAttributes() method which returns
an object of
java.nio BasicFileAttributes
that encapsulates all the attributes associated with the file. That way apart from last modified date you can also get the file creation date and several other attributes.
Java program to find the last modified date of a file
Following program uses both of the above mentioned methods to get the last modified date of a file in Java. Note here that when java.io.File's lastModified method is used it returns the time in milliseconds (long) so SimpleDateFormat is used to format it into dd/MM/yyyy format.
Files.readAttributes()
method returns an instance of BasicFileAttributes. BasicFileAttributes class has methods creationTime()
and lastModifiedTime()
to get the file creation date and last modified date. Both of these methods return an instance of FileTime which is converted to milliseconds and then formatted to the desired format using
SimpleDateFormat.
public class FileDate { public static void main(String[] args) { /*For below Java 7*/ // get the file File f = new File("F:\\NetJS\\programs.txt"); // Create a date format SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // get the last modified date and format it to the defined format System.out.println("File last modified date " + sdf.format(f.lastModified())); /*Java 7 or above using NIO*/ // Get the file Path path = Paths.get("F:\\NetJS\\programs.txt"); BasicFileAttributes attr; try { // read file's attribute as a bulk operation attr = Files.readAttributes(path, BasicFileAttributes.class); // File creation time System.out.println("File creation time - " + sdf.format(attr.creationTime().toMillis())); // File last modified date System.out.println("File modified time - " + sdf.format(attr.lastModifiedTime().toMillis())); } catch (IOException e ) { System.out.println("Error while reading file attributes " + e.getMessage()); } } }
That's all for this topic How to Find Last Modified Date of a File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-