LAST UPDATED: AUGUST 5, 2021
File's last Modified Time in Java
In this post, we are going to get the last modified time of a file by using the Java code. The last-modified time represents the time of last file updation.
Java provides built-in methods such as lastModified()
or getLastModifiedTime()
to get the file last updation time. We can use either File
class of java.io package or Files
class of java.nio package. It's up to you which package you are using.
The lastModified()
methods belong to File
class and returns a time. Whereas the getLastModifiedTime()
method belongs to Files
class and returns time in a long type which further can be converted to datetime.
Time for an Example:
Let's create an example to get the file's last modified time. Here, we are using lastModified()
method of the File class that returns a time in a long type so we need to convert it to time explicitly, as we did in the below example.
import java.io.File;
import java.io.IOException;
import java.time.Instant;
public class Main {
public static void main(String[] args) throws IOException{
try {
File file = new File("abc.txt");
long time = file.lastModified(); // file modified time
System.out.println(time);
// Convert long time to date time
System.out.println(Instant.ofEpochMilli(time));
}catch(Exception e) {
System.out.println(e);
}
}
}
1592912186419
2020-06-23T11:36:26.419Z
Time for another Example:
Let's take another example to get the file's last modified time. Here, we are using getLastModifiedTime()
method of Files
class that returns the time with date. See the below example.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
public class Main {
public static void main(String[] args) throws IOException{
try {
Path path = Paths.get("abc.txt");
FileTime time = Files.getLastModifiedTime(path); // file modified time
System.out.println("Last modified time of the file:");
System.out.println(time);
}catch(Exception e) {
System.out.println(e);
}
}
}
Last modified time of the file:
2020-06-23T11:36:26.419959Z