How to Get File Created Date in Java

In this tutorial, we'll learn how to get the file creation date with an example.

Using Files.getAttribute

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

    private static Optional<Instant> creationTimeWithAttribute(Path path) {
        try {
            final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");

            return Optional
              .ofNullable(creationTime)
              .map((FileTime::toInstant));
        } catch (IOException ex) {
            throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
        }
    }

Using 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:

    private static Instant creationTimeWithBasicAttributes(Path path) {
        try {
            final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            final FileTime fileTime = attr.creationTime();

            return fileTime.toInstant();
        } catch (IOException ex) {
            throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
        }
    }

Complete Program

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;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Optional;

public class CreationDateDemo {

    
    public static void main(String[] args) {

        String fileName = "/home/coding/test.txt";
        Path file = Paths.get(fileName);
        
        System.out.println("creationTime 1: " + creationTimeWithBasicAttributes(file));
        
        System.out.println("creationTime: " + 
            creationTimeWithAttribute(file));
    }
    
    private static Instant creationTimeWithBasicAttributes(Path path) {
        try {
            final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            final FileTime fileTime = attr.creationTime();

            return fileTime.toInstant();
        } catch (IOException ex) {
            throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
        }
    }

    private static Optional<Instant> creationTimeWithAttribute(Path path) {
        try {
            final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");

            return Optional
              .ofNullable(creationTime)
              .map((FileTime::toInstant));
        } catch (IOException ex) {
            throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
        }
    }
}

Comments