如何使用 Java 发现文件的创建时间? [英] How to discover a File's creation time with Java?

查看:13
本文介绍了如何使用 Java 发现文件的创建时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以使用 Java 发现文件的创建时间?File 类只有一个获取上次修改"时间的方法.根据我在 Google 上找到的一些资源,File 类不提供 getCreationTime() 方法,因为并非所有文件系统都支持创建时间的概念.

Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.

我发现的唯一可行的解​​决方案是退出命令行并执行dir"命令,它看起来像是输出文件的创建时间.我想这行得通,我只需要支持 Windows,但我似乎很容易出错.

The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.

是否有任何第三方库可以提供我需要的信息?

Are there any third party libraries that provide the info I need?

更新:最后,我认为购买第三方库不值得,但他们的 API 看起来确实不错,因此对于其他人来说,这可能是一个不错的选择有这个问题.

Update: In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem.

推荐答案

随着 Java 7 的发布,有一种内置的方法可以做到这一点:

With the release of Java 7 there is a built-in way to do this:

Path path = Paths.get("path/to/file");
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();

请务必注意,并非所有操作系统都提供此信息.我相信在这些情况下,这会返回最后修改时间的 mtime.

It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time.

Windows 确实提供了创建时间.

Windows does provide creation time.

这篇关于如何使用 Java 发现文件的创建时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆