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

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.

Also read – date time java program

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.

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 file created date

To determine or find file created date use Files.readAttributes() method which gets instance of BasicFileAttributes.

This BasicFileAttributes is associated with a file in a file system. 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.

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.