Read File Creation Time in Java Example Program

Use Java NIO to Access File Creation TimeStamp


Up until now, there is no direct method in Java to write a consistent logic across different operating systems, to retrieve the file creation timestamp. There are many posts across different OS, writing their own command line approaches to read file creation time stamp. Gone are those days.

Java NIO offers a very elegant way to retrieve a file creation timestamp through BasicFileAttributeView class. And the good news is that this class can be used in a generic fashion across all operating systems. This class exposes a method "creationTime" through which you can read the file creation timestamp of any document.

Read File Creation TimeStamp - Full Java Program


Enough theory, here is a sample code that you can use to fetch the file creation timestamp using Java NIO.
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 FileCreatedTime {
    public static void main(String[] args) throws Exception {
        /* Step  -1: Access the file in Path object */
        Path path = Paths.get("C:", "test.zip");
        /* use readAttributes to read file attributes */
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        /* Print File Creation Time Stamp */            
        System.out.println("File Creation TimeStamp: " + attributes.creationTime());                            
    }
}

For this file, the screenshot in windows properties for created time stamp is given below:
Created: Thursday, 28 June 2012, 10:23:57 PM

The output of the Java program to read a file created time is given below:
File Creation TimeStamp: 2012-06-28T10:23:57.691979Z

NIO is very fast and offers powerful methods to read file metadata. This example proves the capability of the library. See you next time in a different NIO example.

No comments:

Post a Comment