[java] Determine file creation date in Java

There is another similar question to mine on StackOverflow (How to get creation date of a file in Java), but the answer isn't really there as the OP had a different need that could be solved via other mechanisms. I am trying to create a list of the files in a directory that can be sorted by age, hence the need for the file creation date.

I haven't located any good way to do this after much trawling of the web. Is there a mechanism for getting file creation dates?

BTW, currently on a Windows system, may need this to work on a Linux system as well. Also, I can't guarantee that a file naming convention would be followed where the creation date/time is embedded in the name.

This question is related to java date filesystems

The answer is


Java nio has options to access creationTime and other meta-data as long as the filesystem provides it. Check this link out

For example(Provided based on @ydaetskcoR's comment):

Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

The API of java.io.File only supports getting the last modified time. And the Internet is very quiet on this topic as well.

Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.

You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.


As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.

On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;

public class TestFA {
  static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }
  public static void main(String[] args) throws IOException {
    for (String s : args) {
        getAttributes(s);
    }
  }
}

On a Windows system, you can use free FileTimes library.

This will be easier in the future with Java NIO.2 (JDK 7) and the java.nio.file.attribute package.

But remember that most Linux filesystems don't support file creation timestamps.


I've solved this problem using JDK 7 with this code:

package FileCreationDate;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main
{
    public static void main(String[] args) {

        File file = new File("c:\\1.txt");
        Path filePath = file.toPath();

        BasicFileAttributes attributes = null;
        try
        {
            attributes =
                    Files.readAttributes(filePath, BasicFileAttributes.class);
        }
        catch (IOException exception)
        {
            System.out.println("Exception handled when trying to get file " +
                    "attributes: " + exception.getMessage());
        }
        long milliseconds = attributes.creationTime().to(TimeUnit.MILLISECONDS);
        if((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE))
        {
            Date creationDate =
                    new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));

            System.out.println("File " + filePath.toString() + " created " +
                    creationDate.getDate() + "/" +
                    (creationDate.getMonth() + 1) + "/" +
                    (creationDate.getYear() + 1900));
        }
    }
}

in java1.7+ You can use this code to get file`s create time !

private static LocalDateTime getCreateTime(File file) throws IOException {
        Path path = Paths.get(file.getPath());
        BasicFileAttributeView basicfile = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr = basicfile.readAttributes();
        long date = attr.creationTime().toMillis();
        Instant instant = Instant.ofEpochMilli(date);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

This is a basic example of how to get the creation date of a file in Java, using BasicFileAttributes class:

   Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
    BasicFileAttributes attr;
    try {
    attr = Files.readAttributes(path, BasicFileAttributes.class);
    System.out.println("Creation date: " + attr.creationTime());
    //System.out.println("Last access date: " + attr.lastAccessTime());
    //System.out.println("Last modified date: " + attr.lastModifiedTime());
    } catch (IOException e) {
    System.out.println("oops error! " + e.getMessage());
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to filesystems

Get an image extension from an uploaded file in Laravel Notepad++ cached files location No space left on device How to create a directory using Ansible best way to get folder and file list in Javascript Exploring Docker container's file system Remove directory which is not empty GIT_DISCOVERY_ACROSS_FILESYSTEM not set Trying to create a file in Android: open failed: EROFS (Read-only file system) Node.js check if path is file or directory