Find the last modified date and time of a file in Java

In this Java Program, we find out the last time the file was modified by displaying the date and time it was last modified.

This program is easy to implement as there is already a predefined function in Java called lastModified().
We shall learn this method in detail below.

lastModified() method:

  • In Java, we use the lastModified() method to get the file’s last modified time-stamps.
  • The lastModified() function is a part of file class in Java.
  • Return type: This method returns the last modified time and date of the particular file denoted by this abstract path name.
  • Parameters: This function does not accept any parameters.
  • Syntax: file.lastModified() where ‘file’ in the predefined function is the file whose last modified time-stamps we are finding.
  • The lastModified() method returns long value which is measured in milliseconds, representing the time when the file was last modified else returns 0 if the file does not exists or if an exception occurs.
  • We can format the output using SimpleDateFormat to make it readable for humans.

Code to find the last modified date and time:

import java.io.*;
import java.text.SimpleDateFormat;
public class LastModifiedDate
{
    public static void main(String[] args)
    {	
  File file = new File("c:\\example.txt"); //Specifying the file path and file name for real file
  File file1 = new File("c:\\abc.txt");	 //Specifying file path and name which does not exist
  System.out.println("Before Format: " + file.lastModified()); //Using the lastModified() predefined function to show result
    	System.out.println("Before Format: " + file1.lastModified()); //Using the lastModified() predefined function to show exceptions
  SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); //Formating with SimpleDateFormat to make it readable.
    
  System.out.println("After Format: " + sdf.format(file.lastModified()));
  SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yy HH:mm a");
  System.out.println("Alternate Format type: " + sdf2.format(file.lastModified()));
    }
}

Here, we have implemented the code to find the last modified date and time of a file.

Output:

Before Format: 1542478342912
Before Format: 0
After Format: 06/27/2019 11:29:22
Alternate Format Type: 06-27-19 11:29 AM

As seen above, I have clearly found the last modified date and time of file “example.txt”.
I have also shown an example of a file ‘abc.txt’ which does not exist and the exception and value returned.
I have also provided more than one format type to display the last modified date and time of the file.
To read more about date formats, read SimpleDateFormat types.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *