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 :
-
First , we create one ’File’ object by passing the file location to its constructor.
-
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.
-
If your file’s last modified time is before epoch, it will return one negative value.
-
Create one ’Date’ object by passing the last modified time to it.
-
Print out the ’Date’ object.