Java Program to Change Last Modification Time of a File
Last Updated :
22 Oct, 2020
Modifying the date of the file is possible through Java using the File class of Java i.e File.setLastModified() 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.
setLastModified Method
The setLastModified() function is a method that comes predefined in the Java File class. The function sets the last modified time of a file or directory. The function sets the last modified value of the file in milliseconds (long type).
Parameters – A string consisting of the new last-modified time in milliseconds.
Return value – It returns a boolean. (True if the operation succeeds, else false).
If the file doesn’t found in the system default date is printed as of 30/01/1970 as the default file is generated by the system.
Now to change 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.setLastModified(Date.getTime()) method to set the new “Last Modified” date of our file.
Java
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GFG {
public static void main(String[] args)
{
try {
File file = new File( "/home/mayur/file.txt" );
SimpleDateFormat sdf
= new SimpleDateFormat( "mm/dd/yyyy" );
System.out.println(
"Original Last Modified Date : "
+ sdf.format(( long )file.lastModified()));
String newLastModified = "10/10/2020" ;
Date newDate = sdf.parse(newLastModified);
file.setLastModified(newDate.getTime());
System.out.println(
"Latest Last Modified Date : "
+ sdf.format(file.lastModified()));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...