Files Last Modified Time

JavaJavaBeginner
Practice Now

Introduction

Java provides several built-in methods such as lastModified() and getLastModifiedTime() to get the file's last updated time. We can use either the File class of java.io package or Files class of java.nio package to retrieve the last modified time of a file. In this lab, we will use the lastModified() method of the java.io.File class and the getLastModifiedTime() method of the java.nio.Files class to get the last updated time of a file.

Create a Java file

Create a Java file named LastModifiedTime.java at ~/project directory. Use the following command in the terminal:

touch ~/project/LastModifiedTime.java

Import the necessary libraries

Import the java.io.File, java.io.IOException, java.nio.file.Files, java.nio.file.Path, and java.nio.file.attribute.FileTime libraries.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;

Get the last modified time of a file using the lastModified() method

The lastModified() method belongs to the java.io.File class and returns the last modified time of a file as a long value. We can use the Instant.ofEpochMilli() method of the java.time.Instant class to convert the long value to the date and time.

Path filePath = Paths.get("path/to/file");
File file = new File(filePath.toString());
long lastModifiedTime = file.lastModified();
System.out.println("Last modified time: " + Instant.ofEpochMilli(lastModifiedTime));

Replace path/to/file with the actual file path.

After running the above code in the terminal, use the following command:

javac LastModifiedTime.java && java LastModifiedTime

Get the last modified time of a file using the getLastModifiedTime() method

The getLastModifiedTime() method belongs to the java.nio.file.Files class and returns the last modified time of a file along with the date and time.

Path filePath = Paths.get("path/to/file");
FileTime lastModifiedTime = Files.getLastModifiedTime(filePath);
System.out.println("Last modified time: " + lastModifiedTime);

Replace path/to/file with the actual file path.

After running the above code in the terminal, use the following command:

javac LastModifiedTime.java && java LastModifiedTime

Summary

In this lab, we learned how to get the last modified time of a file using Java code. We used the lastModified() method of the java.io.File class and the getLastModifiedTime() method of the java.nio.Files class to retrieve the last modified time of a file. We also learned how to convert a long value to a date and time using the Instant.ofEpochMilli() method of the java.time.Instant class.

Other Java Tutorials you may like