Determine File Creation Date in Java – 在Java中确定文件创建日期

最后修改: 2019年 6月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

JDK 7引入了获取文件创建日期的功能。

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

在本教程中,我们将学习如何通过java.nio访问它。

2. Files.getAttribute

2.Files.getAttribute

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

获取文件创建日期的一个方法是使用方法Files.getAttribute与给定的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.

creationTime的类型是FileTime,但由于该方法返回Object,我们必须对其进行铸造

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

FileTime将日期值作为一个时间戳属性。例如,它可以通过 toInstant()方法被转换为Instant

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

如果文件系统不存储文件的创建日期,那么该方法将返回null

3. Files.readAttributes

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:

另一种获得创建日期的方法是使用Files.readAttributes,对于一个给定的Path,一次性返回一个文件的所有基本属性

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.

该方法返回一个BasicFileAttributes,,我们可以用它来获得一个文件的基本属性。方法creationTime() 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.

这一次,如果文件系统没有存储创建文件的日期,那么该方法将返回最后修改日期。如果最后修改日期也没有存储,那么将返回纪元(01.01.1970)。

4. Conclusion

4.总结

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.

在本教程中,我们已经学会了如何在Java中确定文件的创建日期。具体来说,我们了解到我们可以用Files.getAttributeFiles.readAttributes来做。

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

像往常一样,例子的代码可以在GitHub上找到