How to change(set) or Get the last modification time of a file in java ?


Levels of difficulty: / perform operation:

Problem & Solution(Get last modification time of a file)

This example shows how to get the last modification date of a file using file.lastModified() method of File class.

JAVA Program

import java.io.File;
import java.util.Date;

public class Main {
   public static void main(String[] args) {
      File file = new File("Main.java");
      Long lastModified = file.lastModified();
      Date date = new Date(lastModified);
      System.out.println(date);
   }
}

Output

The above code sample will produce the following result

Sun 16 Aug 10:18:50 PDF 2015


Problem & Solution(Change modification time of a file)

This example shows how to change the last modification time of a file with the help of fileToChange.lastModified() and fileToChange setLastModified() methods of File class .

JAVA Program

import java.io.File;
import java.util.Date;

public class Main {
   public static void main(String[] args) 
   throws Exception {
      File fileToChange = new File
      ("C:/myjavafile.txt");
      fileToChange.createNewFile();
      Date filetime = new Date
      (fileToChange.lastModified());
      System.out.println(filetime.toString());
      System.out.println
      (fileToChange.setLastModified
      (System.currentTimeMillis()));
      filetime = new Date
      (fileToChange.lastModified());
      System.out.println(filetime.toString());
   }
}

Output

The above code sample will produce the following result.The result may vary depending upon the system time.

Sat Oct 18 19:58:20 GMT+05:30 2008
true
Sat Oct 18 19:58:20 GMT+05:30 2008