139

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.

1
  • 2
    Okay, after more discussions and investigations into the filesystems, we have decided that using last modified is sufficient since it would likely have to have been checked along with creation date. Both would need to be checked to determine whether an old file was recently modified and therefore still active. So, just check for the file modified farthest in the past. Thanks for all the input. BTW, I would love to use nio, but the Linux flavor here doesn't support file creation anyway.
    – Todd
    Apr 27, 2010 at 20:07

8 Answers 8

203

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.toPath(), BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
6
  • 16
    This would be best, but it is Java 7. We are still using 6, but I will investigate our upgrade options.
    – Todd
    Apr 27, 2010 at 19:00
  • 8
    use readAttributes(file.toPath(), BasicFileAttributes.class) else you get: no suitable method found for readAttributes(File,Class<BasicFileAttributes>) method Files.<A>readAttributes(Path,Class<A>,LinkOption...) is not applicable (cannot infer type-variable(s) A (argument mismatch; File cannot be converted to Path))
    – Hooli
    Sep 9, 2016 at 15:50
  • 1
    @Hooli No worries, mate! Try this logicbig.com/how-to/java/file-creation-date.html.
    – Socrates
    May 10, 2018 at 13:03
  • 2
    File creation date is not available on JDK 8 (at least) since statx syscall was added in newer Linux kernel version.
    – St.Antario
    Dec 27, 2018 at 13:10
  • 1
    But why the creation time is always the same as the last modified time?
    – LeeR
    Apr 5, 2020 at 13:19
20

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));
        }
    }
}
15

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);
    }
  }
}
2
  • 1
    Do you know how to do it for Android? BasicFileAttributes isn't available as built in API there... Jan 23, 2016 at 23:31
  • This is indeed true, even a call to stat doesn't work. Unless you happen to run a kernel higher than 4.11 with glibc higher than 2.28, and coreutils higher than 8.31, then stat will report the birth of the file. See related answer unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4/… Currently the JDK doesn't use statx syscal.
    – bric3
    Jun 20, 2019 at 13:57
12

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.

6
  • 2
    Yeah, Java 7 would be great as the nio appears to have this in basic attributes. Never thought I would complain about being born too early! ;)
    – Todd
    Apr 27, 2010 at 18:45
  • 7
    The reason the File class doesn't have this capability is that most filesystems don't even track this information. And those that do don't always agree on when it should be updated.
    – Syntactic
    Apr 27, 2010 at 18:50
  • @Syntactic: Actually most filesystems do track this information. Exceptions include ext<=3 and Reiser. FAT, NTFS, HFS, ZFS, and ext4 support it. But it has been slow to propagate through all the layers of Linux and the libraries and commands to make it universally used. Aug 28, 2019 at 17:05
  • @Carl In linux, I am getting modification and creation date as same while using Java NIO. Is it the normal behaviour? Jan 17, 2020 at 11:10
  • @JayeshDhandha, if nothing modifies the file after it's created, I would expect creation and modification times to be equal. You could try changing that by using touch to change the mod time and then checking again. Jan 18, 2020 at 12:14
12

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());
}
1
  • People looking to use this class should note that it started shipping in Java 1.7.
    – jwj
    Mar 13, 2018 at 15:56
10

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.

2
  • Any other way around for linux machines which doesn't support created time ?
    – Maverick
    May 21, 2015 at 6:52
  • Just use a file system that does support file creation timestamps. The Wikipedia article linked suggests ext4 which is quite common now.
    – rbncrthms
    May 21, 2015 at 9:22
2

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());
    }
2
  • could you please elaborate on why do we need this hustle with Instant.ofEpochMilli(date). Thanks Jul 3, 2019 at 11:08
  • @KirillKarmazin Since Java 1.8 we don't need to. We can directly use Instant instant = attr.creationTime().toInstant();.
    – Anonymous
    Apr 7, 2023 at 7:56
0

Basically after you get the creation date from the BasicFileAttributeView object, you should format the date to show:

String modifiedDate;
Path inPath = Paths.get(yourfile.getAbsolutePath());
BasicFileAttributes attr;
try {
    attr = Files.readAttributes(inPath, BasicFileAttributes.class);
} catch (IOException e) {
    attr = null;
}
        
if (attr == null) {
     this.modifiedDate = null;
} else {
    this.modifiedDate = simpleDateFormat.format(attr.creationTime().toMillis());
}
1
  • 2
    Thanks for wanting to contribute. Please don't teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. The FileTime object that you get from creationTime() has a toInstant method that gives you an Instant that you may convert to the desired time zone (for example ZoneId.systemDefault()) and format using a modern DateTimeFormatter. The resulting code will be a bit longer, which is an advantage since it is making more explicit what is happening and therefore reads more clearly and naturally.
    – Anonymous
    Apr 7, 2023 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.