How to get the last modified time of a file in Java
To get the Last Modified Time of a file, we can use the lastModified method of the File class present in the java.io package.
Syntax
public long lastModified()
Parameters
This method doesn’t take any argument.
Return value
This method returns the last modified time as a long value.
Code example
The below code demonstrates how to use the lastModified method to get the last modified time of a file.
import java.io.File;import java.util.Date;class FileLastModifiedTime {public static void main(String[] args) {// File pathString filePath = "test.txt";// create a File objectFile file = new File(filePath);// get lastModified timeLong lastModified = file.lastModified();System.out.println("Last modifiedTime is: " + new Date(lastModified));}}
Explanation
In the above code:
-
In lines 1 and 2: Imported the
FilesandDateclasses. -
In line 7: Created a
Stringvariable holding the path of the file as value (we have atest.txtfile present in the same folder in which the program is executing). -
In line 9: We have created a
Fileobject for thefilePath. -
In line 11:*Used the
lastModifiedmethod to get the last modified time of the file. This will return the time in milliseconds. -
In line 12: Created a new
Dateobject from the last modified time of the file and printed it.