Java Program to get the last modified date and time of a file

Write a Java program to get the last modified date and time of any file :

In this tutorial, we will learn how to print the last modified date and time of a file in Java. For this, we will first create one ‘File’ object. To create one ‘File’ object, pass the file’s location to the constructor. If you want to get the full path of a file, open one terminal and drag-drop one file on the terminal. It will print its full path.

Let’s take a look into the program :

import java.io.File;
import java.util.Date;

public class Main {

    public static void main(String[] args) {
        File file = new File("E:/song.mp3");
        long lastModified = file.lastModified();

        System.out.println(new Date(lastModified));
    }
}

Output :

Mon Oct 12 19:18:38 IST 2017

Explaination :

  1. First , we create one ’File’ object by passing the file location to its constructor.

  2. Then using ’lastModified()’ method, we got the last modified time .It returns the time in milliseconds since epoch(00:00:00 GMT, January 1, 1970). The return value is long. If the file is not available, it returns 0L. If any IO error occurs, 0L will be returned.

  3. If your file’s last modified time is before epoch, it will return one negative value.

  4. Create one ’Date’ object by passing the last modified time to it.

  5. Print out the ’Date’ object.

Similar tutorials :