Find last modified time of a File in Java

Problem Statement:

How to find last modified time of a File in Java?

Find last modified time of a File in Java

Find last modified time of a File

Description

To find last modified time of a file in java, we have to use File.lastModified() method of File class passing the new instance of file pathname as shown below.  This method returns the long value of the time the file was last modified (measured in millisecods).

Returns 0L in case of file does not exist or IO exception.

Sample Code to find last modified time of a file in java

package com.stixs.java.io;

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

public class STXFindLastModifiedDateOfFile {
   public static void main(String[] args) {
 
      File sampleFile = new File("c:\\technostixs\\java\\samplefile.txt");

      //Returns the time that the file denoted by this abstract 
      //pathname was last modified. 
      System.out.println("STXFindLastModifiedDateOfFile:: 
         Last modified date of samplefile.txt is : " 
         + sampleFile.lastModified());
 
      //Constructs a SimpleDateFormat using the given pattern
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");

      System.out.println("STXFindLastModifiedDateOfFile::Last modified
        date of samplefile.txt after Formatting is " 
         + sdf.format(sampleFile.lastModified()));
   }
}

Output

Case 1: There should be a fail named samplefile.txt at c:\\technostixs\\java path.

STXFindLastModifiedDateOfFile:: Last modified date of samplefile.txt is : 1414369338783
STXFindLastModifiedDateOfFile:: Last modified date of samplefile.txt after Formatting is 2014.10.26 AD at 20:22:18 EDT

Case 2 : If the file samplefile.txt doesnot exist, the lastModified() method would return below results.

STXFindLastModifiedDateOfFile:: Last modified date of samplefile.txt is : 0
STXFindLastModifiedDateOfFile:: Last modified date of samplefile.txt after Formatting is 1969.12.31 AD at 19:00:00 EST

Java API used to find last modified time of a file in java

File

Find last modified time of a File in Java

Find last modified time of a File in Java

File.lastModified()

Find last modified time of a File in Java

Find last modified time of a File in Java

Reference

Refer below path to get the complete details about Java IO File class.

http://docs.oracle.com/javase/8/docs/api/java/io/File.html

——————————————————————————–

You may also like this

——————————————————————————–

About TechnoStixs.com

Delete File in Java

TechnoStixs.com is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.

1,266 total views, 1 views today

Add comment