Java Program to Get Last Modification Date of a File
The last modifying date of the file can get through Java using the File class of Java i.e File.LastModified() method.
Java File Class
The File class is Java’s representation of a file or directory pathname. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.
The class named File of java.io package represents both file and directory in the system. This class provides various methods to operate on files and directories. It contains a method called lastModified() which returns the last modified date of a file or directory in form of a long millisecond epoch value, which can be made readable using format() method of SimpleDateFormat class. The output can be displayed in any desired format using SimpleDateFormat class. This method can be used in all Java versions. lastModified() method returns 0l if the file does not exist. 0l means the number zero of type long. It uses this constructor to instantiate a Date that refers to zero milliseconds after the ‘epoch’ i.e, January 1, 1970, 00:00:00 GMT or January 1, 1970, 05:30 AM IST.
public long lastModified()
Now to get the last modified date of a file, follow the given steps.
- First, use the SimpleDateFormat(“mm/dd/yyyy”) constructor to make a new SimpleDateFormat class instance.
- Then, construct a String object with the “mm/dd/yyyy” format.
- Use the parse(String) method of the SimpleDateFormat class to create a new Date object with the date value of the String we created.
- Finally, use File.LastModified() method to set the new “Last Modified” date of our file.
Note: The program does not run in an online IDE. Please use an offline IDE and then set the path of the file.
File1 exists in the system while File2 does not exist in the system. Therefore, in the case of file2, 0l is returned while in the case of file1 the last modified date is returned.