【问题标题】:How to get proper file creation date of file?如何获取文件的正确文件创建日期?
【发布时间】:2014-01-28 19:30:41
【问题描述】:

我不需要上次修改时间,也不需要上次文件访问时间,而是文件创建时间。我还没有找到这方面的信息。也许一些库?

Path p = Paths.get(f.getAbsoluteFile().toURI());
BasicFileAttributes view = null;
try {
    view = Files.getFileAttributeView(p,
                            BasicFileAttributeView.class).readAttributes();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
FileTime creationTime = view.creationTime();

在此代码中创建时间无效并返回今天日期。

操作系统:Windows 7 Java:SE-1.7

【问题讨论】:

    标签: java file


    【解决方案1】:

    正如 yshavit 所说,并非所有操作系统都会记录创建日期。但是,您应该能够使用java.nio.file 来确定具有此功能的操作系统的此信息 - 请参阅files.getAttribute 的文档 - 请注意BasicFileAttributeView 有一个creationTime 字段。

    您可以使用FileSystems.getDefault(); 来确定当前操作系统支持哪些FileAttributeViews。

    Files.getAttribute(path, "basic:createdAt"); 将返回一个FileTime 对象,其中包含在支持BasicFileAttributeView 的系统上创建文件的日期。您必须将其转换为 java.util.Date 对象,但我会让您自己解决。

    进一步阅读

    • 蔚来APIgetAttribute()
    • 蔚来APIBasicFileAttributeView
    • tutorial 用于使用 readAttributes()
    • 关于使用 FileAttributes 的综合 tutorial
    • 关于同一主题的另一个 * thread

    【讨论】:

      【解决方案2】:

      如何获取Java中文件的创建日期,使用BasicFileAttributes类,这是一个例子:

         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());
      
          } catch (IOException e) {
          System.out.println("oops error! " + e.getMessage());
          }
      

      【讨论】:

        【解决方案3】:

        您无法在所有系统中执行此操作,因为并非所有系统都记录该信息。例如,Linux 没有。见this SO thread

        许多程序通过复制文件、对副本进行更改、然后将副本移动到原始文件的位置来“修改”文件。所以对于那些人来说,创建和最后修改之间没有有意义的区别。

        【讨论】: