Extract Created and Modified Datetime of Files in Java

In Java, there is a class called FileSystem in the java.nio.file package. This class helps in working with file systems. It acts as a way to access and perform operations on files and directories in a file system. It provides a consistent way to work with different file systems, making it easier to handle files and directories regardless of the underlying system.

One useful method in the FileSystem class is readAttributes(). This method allows you to get information about a file, such as its metadata or attributes. You can retrieve details like the file's creation time, access time, and last modified time using this method. By using readAttributes(), you can access specific information about a file without having to read its contents or perform additional operations.

Here's an example code to demonstrate how to get the file creation, last access and last modified date and time in Java:

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 Example {

   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 output of the above code is as follows:

File creationTime: 2022-06-05T10:37:55.9977076Z
File lastAccessTime: 2023-01-11T06:58:31.2183413Z
File lastModifiedTime: 2022-06-05T10:39:40.1095374Z

In this code snippet, there is a string variable named fileName that holds the path of a specific file. The Path file = Paths.get(fileName); line converts the file path string into a Path object. The Paths.get() method is used to create a Path instance representing the file. The Files.readAttributes(file, BasicFileAttributes.class); line reads the basic file attributes of the specified file. It uses the Files.readAttributes() method to get the BasicFileAttributes object containing information about the file, such as its size, timestamps, and other basic properties. The attr.creationTime() method is used to retrieve the creation time of the file from the BasicFileAttributes object. Similarly, attr.lastAccessTime() retrieves the last access time of the file, and attr.lastModifiedTime() retrieves the last modified time of the file. Finally, the program prints the obtained information to the console using System.out.println().