从Java获得毫秒分辨率的文件mtime [英] Get file mtime with millisecond resolution from Java
问题描述
当我使用 Files.getLastModifiedTime
从Java读取文件的 mtime
时,返回值被截断为整秒。我知道这可以在其他系统上运行,以获得毫秒级的分辨率,那么我的可能有什么不同呢?
When I read the mtime
of a file from Java using Files.getLastModifiedTime
, the return value is truncated to whole seconds. I know this works on other systems to get mtimes with millisecond resolution, so what could be different about mine?
这是一个完整的独立测试,可以编译和运行:
Here is a complete standalone test which compiles and runs:
import java.nio.file.attribute.FileTime;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) throws java.io.IOException {
FileTime timestamp = Files.getLastModifiedTime(Paths.get("/tmp/test"));
System.out.println(timestamp.toMillis());
}
}
输出是(使用我的特定测试文件) 1405602038000
,而 ls
显示:
The output is (with my particular test file) 1405602038000
, whereas ls
shows:
$ ls --full-time /tmp/test
-rw-rw-r-- 1 daniel daniel 0 2014-07-17 16:00:38.413008992 +0300 /tmp/test
我希望Java输出 1405602038413
。
I would expect the Java output to be 1405602038413
.
我在Linux上使用ext4运行。我尝试了openjdk 1.7和Oracle jdk 1.8。
I'm running on Linux with ext4. I tried both openjdk 1.7 and Oracle jdk 1.8.
推荐答案
增加了在* nix系统上获得更高精度的文件时间戳的能力在Java 8中通过此提交,然而,在本机方面,它需要POSIX 2008合规:
The ability to get file timestamps on *nix systems with higher precision was added in Java 8 by this commit, however, on the native side, it requires POSIX 2008 compliance:
#if (_POSIX_C_SOURCE >= 200809L) || defined(__solaris__)
(*env)->SetLongField(env, attrs, attrs_st_atime_nsec, (jlong)buf->st_atim.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_mtime_nsec, (jlong)buf->st_mtim.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_ctime_nsec, (jlong)buf->st_ctim.tv_nsec);
#endif
显然,你正在使用的Java版本没有设置它,所以时间戳的纳秒部分不可用并且保持为零。
And, apparently, the Java build you are using doesn't set it, so nanoseconds part of the timestamp is not available and stays zero.
这篇关于从Java获得毫秒分辨率的文件mtime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!