新Date()和文件创建日期之间的奇怪区别

时间:2009-09-17 11:56:30

标签: java file date

我正在运行一些测试来证明一个概念,我只是编写了这段代码并发现了一个奇怪的情况:

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次尝试中。

我在这里缺少什么?

是否有任何方法可以保证新的Date()早于文件创建?

4 个答案:

答案 0 :(得分:5)

文件系统日期粒度通常为一秒(取决于实际的文件系统,它也可能更糟)。创建文件时,创建时间将四舍五入。

答案 1 :(得分:2)

上次修改的粒度可能小于毫秒。

答案 2 :(得分:2)

我知道 Date对象在我们的机器上给出了毫秒,但只有每15.5毫秒。具体来说,在我们的日志模块中,我们看到日期之间的差异为:15ms,16ms,31ms,47ms ......

这可以解释至少15ms的差异。


除此之外,根据我的经验,文件操作不应过多依赖于精确的日期。我已经看到很多依赖项或最新的检查器的实现,其容差大约为300ms到2s (对于远程文件更多)。因此,如果依赖文件位于后面或前面(但不超过300毫秒),它们会认为它是最新的。

答案 3 :(得分:0)

也许编译器重新排序指令的执行方式?

或许,如果您的真实意图不需要毫秒或更高的精度,则更准确的测试应该包括两个指令之间的一些休眠时间。

相关问题