How to get file last modified date in java

Let’s learn how to get file last modified date in java.

How to get file last modified date in java

Get last modified date of a file using java is one of the common interview question in java.

To get last modified date use lastModified() method of class File.

how to get file last modified date in java

lastModified() method return a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.

Also read – current date time java program

The value may be negative indicating the number of milliseconds before the epoch.

Here’s the java program.

import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class LastModifiedDateDemo
{
   public static void main(String[] args)
   {
      File file = new File("d:\\modifiedFile.txt");
      System.out.println("Before - file last modified date: " + file.lastModified());
      SimpleDateFormat sim = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
      System.out.println("After - file last modified date: " + sim.format(file.lastModified()));
   }
}


Output:

Before – file last modified date: 1486480590836
After – file last modified date: 02/07/2014 05:14:10


java get file creation date

To get file creation date use BasicFileAttributes from the Path.

Basic file attributes are attributes that are common to many file systems and consist of mandatory and optional file attributes as defined by this interface.

Also read – how to rename file in java

In the below java program first create File object from file path.

This object reads Path attributes using Files.readAttributes. Here we can access creation date and time.

Also read – java create new file

This time is FileTime object and it is converted to Date and formatted.

Here’s program on java get file creation date.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileCreatedDate
{
   public static void main(String[] args) throws IOException
   {
      File fl = new File("B:\\Demo.txt");
      BasicFileAttributes bfa;
      try
      {
         bfa = Files.readAttributes(fl.toPath(), BasicFileAttributes.class);
         FileTime ft = bfa.creationTime();
         String strPattern = "yyyy-MM-dd HH:mm:ss";
         SimpleDateFormat sdf = new SimpleDateFormat(strPattern);
         String strFormat = sdf.format(new Date(ft.toMillis()));
         System.out.println("java file created date is: " + strFormat);
      }
      catch(IOException ex)
      {
         ex.printStackTrace();
      }
   }
}


Output:

java file created date is: 2005-05-23 05:23:14


So this all about getting last modified date in java. I hope this tutorial will be helpful for freshers in java.