Question:
How to change the file last modified date in Java?
Answer:
Use File.setLastModified()
Code:
import java.io.*; import java.util.*; import java.text.*; public class ChangeModificationTime { public static void main(String[] args) { File file = new File("ChangeModificationTime.java"); Date date = new Date(file.lastModified()); System.out.println(date); try { String str = "01/31/1998"; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date newDate = sdf.parse(str); file.setLastModified(newDate.getTime()); } catch(ParseException e) { System.out.println("ParseException"); } date = new Date(file.lastModified()); System.out.println(date); } }
Output:
$ ls -l ChangeModificationTime.java -rw-rw-r-- 1 dennis dennis 664 Feb 26 12:44 ChangeModificationTime.java $ java ChangeModificationTime Thu Feb 26 12:44:31 EST 2015 Sat Jan 31 00:00:00 EST 1998 $ ls -l ChangeModificationTime.java -rw-rw-r-- 1 dennis dennis 664 Jan 31 1998 ChangeModificationTime.java