How to Get File Creation Time in Java

Managing files often involves not only reading and writing content but also retrieving metadata such as creation time. In this blog post, we'll explore different methods to access a file's creation time using Java. 

Method 1: Using java.nio.file.Files

The java.nio.file.Files class provides a modern way to access a file's creation time:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class FileCreationTimeExample {
    public static void main(String[] args) {
        Path path = Paths.get("path/to/your/file.txt");
        try {
            BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime creationTime = attributes.creationTime();
            System.out.println("File Creation Time: " + creationTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Method 2: Using java.io.File

The java.io.File class can also be used to retrieve a file's creation time:

import java.io.File;

public class FileCreationTimeExample {
    public static void main(String[] args) {
        File file = new File("path/to/your/file.txt");
        long creationTime = file.lastModified();
        System.out.println("File Creation Time: " + creationTime);
    }
}

Keep in mind that the lastModified() method in this approach returns the time the file was last modified, which may not be the same as the actual creation time. 

Method 3: Using java.nio.file.Path and java.nio.file.attribute.FileTime

Another way to access the creation time is by directly querying the FileTime attribute of a java.nio.file.Path object:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;

public class PathCreationTimeExample {
    public static void main(String[] args) {
        Path path = Paths.get("path/to/your/file.txt");
        try {
            FileTime creationTime = Files.getCreationTime(path);
            System.out.println("File Creation Time: " + creationTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Conclusion

In this post, we have seen how to use java.nio.file.Files class, the java.io.File class, or directly querying FileTime attributes to accurately retrieve creation time information. These methods provide you with the means to work with file metadata and enhance your file management capabilities in Java.

Comments