Get file mtime with millisecond resolution from Java

。_饼干妹妹 提交于 2019-11-29 09:45:38

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

And, apparently, the Java build you are using doesn't set it, so nanoseconds part of the timestamp is not available and stays zero.

I looked at the source code:

In the Java 7 case, the method gives the last modified timestamp with 1 second precision:

In the Java 8 case, it looks like it should give microsecond precision:

But in either case, the code doesn't seem to provide a way to get the timestamp with a different precision.

It seems to be fixed in java 9

  • Oracle jdk 9.0.4 - Files.getLastModifiedTime gives millisecond resolution
  • Oracle jdk 1.8.162 - Files.getLastModifiedTime gives second resolution

You can use the simple date format to display time is milliseconds:

java.nio.file.attribute.FileTime time = java.nio.file.Files.getLastModifiedTime(java.nio.file.Paths.get("/tmp/test"))
java.text.SimpleDateFormat dateformat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(dateformat.format(time.toMillis()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!