Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

JDK 7 introduced the ability to get a file's creation date.

In this tutorial, we'll learn how we can access it through java.nio.

2. Files.getAttribute

One way to get a file's creation date is to use the method Files.getAttribute with a given Path:

try {
    FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
} catch (IOException ex) {
    // handle exception
}

The type of creationTime is FileTime, but due to the fact that the method returns Object, we have to cast it.

FileTime holds the date value as a timestamp attribute. For instance, it can be converted to Instant with the toInstant() method.

If the file system doesn't store the file's creation date, then the method will return null.

3. Files.readAttributes

Another way to get a creation date is with Files.readAttributes which, for a given Path, returns all the basic attributes of a file at once:

try {
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    FileTime fileTime = attr.creationTime();
} catch (IOException ex) {
    // handle exception
}

The method returns a BasicFileAttributes, which we can use to obtain a file's basic attributes. The method creationTime()  returns creation date of file as FileTime.

This time, if the file system doesn't store the date of creating a file, then the method will return last modified date. If the last modified date is not stored as well, then the epoch (01.01.1970) will be returned.

4. Conclusion

In this tutorial, we've learned how to determine the file creation date in Java. Specifically, we learned that we can do it with Files.getAttribute and Files.readAttributes.

As always, the code for examples is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!