Java File lastModified() method with examples

April 28, 2020 No comments Java IO File Examples lastModified

1. Introduction

The lastModified() method returns the time of the last file modification.

2. Method signature

public long lastModified()


  • method does not take any parameter


  • long - a 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


  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Prints the lastModified of a not existing file, a directory and existing file


import java.time.Instant;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f1 = new File("/tmp/frontbackend.txt"); // does not exist
            File f2 = new File("/tmp");
            File f3 = new File("/tmp/exists.txt");

            System.out.printf("/tmp/frontbackend.txt - %s%n", f1.lastModified()); // 0 
            System.out.printf("/tmp - %s%n", f2.lastModified());
            System.out.printf("/tmp/exists.txt - %s%n", Instant.ofEpochMilli(f3.lastModified()));

        } catch (Exception e) {

The output:

/tmp/frontbackend.txt - 0
/tmp - 1588103611000
/tmp/exists.txt - 2020-04-28T19:53:31Z

4. Conclusion

In this article, we presented a way to check the last modification date using Java IO API. The lastModified method returns time in milliseconds that could be easily converted to the Java 8 Instant object using Instant.ofEpochMilli method.

{{ message }}

{{ 'Comments are closed.' | trans }}