How to get last modification date of a file in Java



Problem Description

How to get last modification date of a file?

Solution

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

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

Result

The above code sample will produce the following result.

Tue 12 May 10:18:50 PDF 2009

The following is an another sample example of last modification date of a file

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

public class GetFileLastModifiedExample {
   public static void main(String[] args) {
      File file = new File("Main.java");
      System.out.println("Before Format : " + file.lastModified());
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
      System.out.println("After Format : " + sdf.format(file.lastModified()));
   }
}

The above code sample will produce the following result.

Before Format : 0
After Format : 01/01/1970 05:30:00
java_files.htm
Advertisements