Extract Created and Modified Datetime of Files in Java
In java there are different packages and API which is used to perform different functions. java.nio.file is one such packages.This package is used to access FileSystem class and contain different methods. To get the file metadata or attribute, and the file creation creation time, file access time and last modified time, the readAttributes() method is used.
The program below shows how to get the file creation, last access and last modified datetime:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class ExtractFileMetadataExample {
public static void main(String[] args) {
//file location
String fileName = "C:\\Users\\USERNAME\\Documents\\testfile.docx";
try {
Path file = Paths.get(fileName);
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("File creationTime: " + attr.creationTime());
System.out.println("File lastAccessTime: " + attr.lastAccessTime());
System.out.println("File lastModifiedTime: " + attr.lastModifiedTime());
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code gives the following output:
File lastAccessTime: 2023-01-11T06:58:31.2183413Z
File lastModifiedTime: 2022-06-05T10:39:40.1095374Z
Here in the above example code, the program displays the creation, last access and last modified datetime of a certain file. We have created a string “fileName” and mention the path of a file. The try statement allows you to write a block of code that is to be checked for errors while being executed. If there is any exception, a catch block will be executed. In the try block, We have created a Path object using the Paths.get() method. This Paths.get() method returns a Path object by converting a given string into a Path. Next, the Files.readAttributes() method from java.nio.file.Files package is used to retrieve attributes of the file. The Files.readAttributes() method returns an object of BasicFileAttributes class.The BasicFileAttributes contain information related to files like creation time, last access time, last modified time and many more. We printed the file creation time, last access and last modified time by calling creationTime(), lastAccessTime() and lastModifiedTime() method of the BasicFileAttributes class object.