我正在运行一些测试来证明一个概念,我刚刚编写了这段代码,发现了一个奇怪的情况:
public class Test {
public static void main(String[] args) {
Date now = new Date();
File file = new File("/root/batch-experiments/test.txt");
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("cannot create file...");
}
System.out.println(MessageFormat.format("Checking File {0}! Last Modified time is {1}. Must be newer than {2}", file.getName(),
file.lastModified(), now.getTime()));
if (file.lastModified() >= now.getTime()) {
//ignore...
} else {
System.out.println(MessageFormat.format("File {0} is out of date and was ignored.", file));
}
}
输出是:
Checking File test.txt! Last Modified time is 1,253,187,650,000. Must be newer than 1,253,187,650,496
File /root/batch-experiments/test.txt is out of date and was ignored.
这怎么可能? 文件修改时间不应该在新日期时间之后吗? 每 4/5 次尝试中就有 1 次发生这种情况。
我在这里缺少什么?
有什么方法可以保证 new Date() 早于文件创建?
最佳答案
文件系统日期粒度通常为一秒(根据实际文件系统,也可能更差)。创建文件时,创建时间会四舍五入。
关于java - new Date() 和文件创建日期之间的奇怪区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1438394/