How to get the last modified date and time of a file or directory in Java

Sometimes before processing a file, you want to check it's last modified date to avoid processing an old file. Though some programmers prefer to attach date in the file name itself, I don't find it a cleaner approach. For example, suppose you are downloading closing prices of stocks and processing at the start of the day and loading into the database. In order to accidently process an old file, you can check the last modified date before processing and if it's in the acceptable range, you can process the file. You can get the last modified date of a file in Java by using java.io.File class. This is a class which represents both file and directory in Java. It contains a method called lastModified() which returns the last modified date of the file. This method returns a long millisecond epoch value, which you can convert to more readable dd MM yyyy HH:mm:sss format by using the SimpleDateFormat class of JDK.  In this article, I'll tell you how to get the last modified date of file and directory in Java.


The above solution is to keep all Java versions in mind i.e. it will work in all Java version from JDK 1 to JDK 8, but if you are writing new code and have access to much improved and new Java 7 and Java 8 API, you should use the  public static FileTime getLastModifiedTime(Path path, LinkOption... options) method which returns a file's last modified time.

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed. You can also get last modified time by using readAttributes() method and using the lastModifiedTime attribute.


Btw, you can also change the last modified time of a file by using the public static Path setLastModifiedTime(Path path, FileTime time) method. This one updates a file's last modified time attribute. The file time is converted to the epoch and precision supported by the file system. Converting from finer to coarser granularities may result in precision loss.

The behavior of this method when attempting to set the last modified time when it is not supported by the file system or is outside the range supported by the underlying file store is not defined. It may or not fail by throwing an IOException.



How to find the last modified date of a file in Java

Before Java 7 e.g. in JDK 1.6, You can use the lastModified() method of File class to get the last updated time. Just create a File object by passing the path as String to File class and call the last modified method as shown below:


File source = new File(".project");
long lastModified = source.lastModified();

This lastModified time is the long millisecond value from epoch, 1st January 1970. You can further convert this into a java.util.Date object by following steps given here.

In JDK 7 and with new file API, the java.nio.file, you can use the Files class to retrieve the last modified time of a file in Java as shown in the following example:

 Path location = Paths.get(".project");
 FileTime lastModifiedTime = Files.getLastModifiedTime(location,
                  LinkOption.NOFOLLOW_LINKS);

You can further convert the FileTime to long millisecond value by using the toMillis() method and then you can create the java.util.Date object from there as shown earlier.  You can also read the Well-Grounded Java Developer  to learn more about the new file API of Java 7, along with several other tips for experienced Java programmers on concurrency and polyglot programming e.g. using Scala and Closure.


How to get the last modified date of a file or directory in Java



How to get the last modified date of a directory in Java

The steps to get the last updated time for both file and directory is same, as java.io.File represents both file and directory. The only difference is you pass the path of the file instead of a file.

File settings = new File(".settings");
long lastChanged = settings.lastModified();


You can also further read, Java SE 8 for Really Impatient By Cay S. Horstmann to learn more about how to use new File API of JDK 7 along with Java 8 goodies.

How to get the lastModifiedTime of a file or directory in Java 8



Java Program to get the last modified date of file or directory

Here is our complete Java program to find the lastModifiedTime of a file or directory in Java. In this program, I have shown both old and new way of retrieving the last modified time of a file in Java. Before JDK 7, you can use the lastModified() method of File class to retrieve this value.

Post JDK 1.7 version i.e. in both Java 7 and 8, you can use the Files.getLastModifiedTime() to retrieve the last modified time and Files.setLastModifiedTime() to update this attribute of the file.  I also suggest reading a good Java book which covers both JDK 7 and 8 to learn more about the new File API. It contains lots of utility methods to make your day-to-day life simpler while dealing with files and directories in Java. You can take a look at Java SE8 for Programmers by Dietel and Dietel

Here is a nice summary of various File utility methods from Java 6 to Java 7, you can use this handy list whenever you search for an equivalent method in new file API.

How to find lastModifiedTime of File in Java example



How to find lastModifiedTime of File in Java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Java Program to find the last modified date of a file
 * and directory in Java. 
 * 
 * @author WINDOWS 8
 *
 */
public class Pattern {

  public static void main(String args[]) throws IOException{

    // Example 1 - getting last modified date of a file in Java
    System.out.println("Finding the last modified time of file and directory in Java 6 and before");
    File source = new File(".project");
    long lastModified = source.lastModified();
    String time = format(lastModified);
    System.out.printf("file %s was last modified at %s %n", source.getName(),
        time);

    // Example 2 - how to get last modified date of a directory in Java
    File settings = new File(".settings");
    long lastChanged = settings.lastModified();
    String lastUpdated = format(lastChanged);
    System.out.printf("directory %s was last updated at %s %n",
        settings.getName(), lastUpdated);
    
    // Finding last modified time of a file in Java 7 and 8
    System.out.println("Finding the last modified time of file and directory in Java 7 and 8");
    Path location = Paths.get(".project");
    FileTime lastModifiedTime = Files.getLastModifiedTime(location, LinkOption.NOFOLLOW_LINKS);
    String lastModifiedTimeAsString = format(lastModifiedTime.toMillis());
    System.out.printf("file %s was last modified at %s %n", location,lastModifiedTimeAsString);
    
  }

  public static String format(long time) {
    DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    return sdf.format(new Date(time));
  }

}
Output
Finding the last modified time of file and directory in Java 6 and before
file .project was last modified at 04-06-2015 00:27:06 
directory .settings was last updated at 04-06-2015 00:27:06 
Finding the last modified time of file and directory in Java 7 and 8
file .project was last modified at 04-06-2015 00:27:06 


That's all about how to get the last modified date of a file or directory in Java. As I said, same class java.io.File is used to represent both file and directory and it also provides a lastModified() method, which can be used to get the time when that particular file or directory was last modified. If you are using Java 7 or Java 8 then you can also use the java.nio.file, the new File API to both retrieve and update the lastModifiedTime attribute of a file in Java. It provides Files class to retrieve various file attributes. I also suggest you read a good core Java book which covers JDK 7 or 8 e.g. Java: A Beginner's Guide by Herbert Schildt from Oracle itself, it covers Java 8 as well.



Other Java File and Directory tutorials you may like to explore 
  • How to delete a directory with files and subdirectory in Java? (tutorial)
  • How to read Microsoft XLS file in Java? (example
  • Right way to Read Zip Files in Java (example
  • How to work with RandomAccessFile in Java? (demo
  • How to read/write text files in Java? (solution
  • Difference between getPath(), getCannonicalPath() and getAbsolutePath() in Java? (answer
  • How to read/write Properties files in Java? (example
  • How to make hidden file in Java? (program
  • How to use Memory Mapped File in Java? (code
  • How to modify an Excel file in Java using Apache POI library (tutorial)
  • How to copy File in Java? (solution
  • How to read File line by line in Java using BufferedReader? (example
  • How to check File Permission in Java? (program
  • How to change File Permission in Java? (solution
  • How to create File and Directory in Java? (solution
  • How to check hidden file in Java? (solution
  • How to read File in one line in Java 8? (example


No comments :

Post a Comment