Java Examples - Setting File Date


Advertisements


Problem Description

How to change the last modification time of a file ?

Solution

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 .

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());
   }
}

Result

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

The following is another sample example of last modification time of a file in java

import java.io.File;
import java.text.SimpleDateFormat;

public class GetFileLastModifiedExample { 
   public static void main(String[] args) { 
      File f1 = new File("C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\abc.png");
      System.out.println("Before Format : " + f1.lastModified());
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
      System.out.println("After Format : " + sdf.format(f1.lastModified()));
   }
}

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

Before Format : 1473659371467
After Format : 09/12/2016 11:19:31

java_files.htm

Advertisements