beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to get the last modified date of a file in java

By Chaitanya Singh | Filed Under: Java I/O

Here we will learn how to get the last modified date of a file in java. In order to do this we can use the lastModified() method of File class. Following is the signature of this method.

public long lastModified()

It returns the time that the file denoted by this abstract pathname was last modified. The value returned by this method is in milliseconds so in order to make it readable, we can format the output using SimpleDateFormat.

Complete code:

Here we are fetching the last modified date of file “Myfile.txt” which is present in drive “C”. Since the value returned by method is not readable, we are using format() method of SimpleDateFormat class to format it.

import java.io.File;
import java.text.SimpleDateFormat;
public class LastModifiedDateExample
{
    public static void main(String[] args)
    {	
        //Specify the file path and name
	File file = new File("C:\\Myfile.txt");
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	System.out.println("Last Modified Date: " + sdf.format(file.lastModified()));
    }
}

Output:

Last Modified Date: 01/03/2014 22:41:49

We can format and display the output in any desired format. For example if we use the following pattern:

SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yy HH:mm a");
System.out.println("Last Modified Date: " + sdf2.format(file.lastModified()));

We will get the below output for above pattern:

Last Modified Date: 01-03-14 22:41 PM

There are several other patterns which you can use to get the output in desired form. To read more about date formatting refer SimpleDateFormat javadoc.

Enjoyed this post? Try these related posts

  1. How to read file in Java – BufferedInputStream
  2. How to write to file in Java using BufferedWriter
  3. Append to a file in java using BufferedWriter, PrintWriter, FileWriter
  4. How to check if a File is hidden in Java
  5. How to write to a file in java using FileOutputStream
  6. Java – Find files with given extension

Comments

  1. rahul says

    November 24, 2015 at 7:28 AM

    hi
    could you please help me in writing a java code for copy text written using Mangal.ttf font in one text file to another.

    Reply

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap