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.
public long lastModified()
This method doesn’t take any argument.
This method returns the last modified time as a long value.
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));}}
In the above code:
In lines 1 and 2: Imported the Files
and Date
classes.
In line 7: Created a String
variable holding the path of the file as value (we have a test.txt
file present in the same folder in which the program is executing).
In line 9: We have created a File
object for the filePath
.
In line 11:*Used the lastModified
method to get the last modified time of the file. This will return the time in milliseconds.
In line 12: Created a new Date
object from the last modified time of the file and printed it.