file.createnewfile()创建文件,并在实际创建时间之前用最后修改的时间创建文件
-
01-10-2019 - |
题
我正在使用 jpoller 要检测特定目录中文件的更改,但是它缺少文件,因为它们最终比实际创建时间更早地使用时间戳。这是我测试的方式:
public static void main(String [] files)
{
for (String file : files)
{
File f = new File(file);
if (f.exists())
{
System.err.println(file + " exists");
continue;
}
try
{
// find out the current time, I would hope to assume that the last-modified
// time on the file will definitely be later than this
System.out.println("-----------------------------------------");
long time = System.currentTimeMillis();
// create the file
System.out.println("Creating " + file + " at " + time);
f.createNewFile();
// let's see what the timestamp actually is (I've only seen it <time)
System.out.println(file + " was last modified at: " + f.lastModified());
// well, ok, what if I explicitly set it to time?
f.setLastModified(time);
System.out.println("Updated modified time on " + file + " to " + time + " with actual " + f.lastModified());
}
catch (IOException e)
{
System.err.println("Unable to create file");
}
}
}
这是我要输出的东西:
-----------------------------------------
Creating test.7 at 1272324597956
test.7 was last modified at: 1272324597000
Updated modified time on test.7 to 1272324597956 with actual 1272324597000
-----------------------------------------
Creating test.8 at 1272324597957
test.8 was last modified at: 1272324597000
Updated modified time on test.8 to 1272324597957 with actual 1272324597000
-----------------------------------------
Creating test.9 at 1272324597957
test.9 was last modified at: 1272324597000
Updated modified time on test.9 to 1272324597957 with actual 1272324597000
结果是种族条件:
- jpoller记录上次检查的时间为xyz ... 123
- 在xyz创建的文件... 456
- 文件最后修饰的时间戳实际读取xyz ... 000
- JPoller在时间戳大于XYZ的新/更新文件... 123
- jpoller忽略了新添加的文件,因为xyz ... 000小于xyz ... 123
- 我把头发拉了一段时间
我尝试挖掘代码,但两者都 lastModified()
和 createNewFile()
最终解决本机通话,所以我剩下的信息很少。
为了 test.9
, 我输了957毫秒. 。我可以期待什么样的准确性?我的结果会因操作系统或文件系统而变化吗?建议的解决方法?
注意:我目前正在使用XFS文件系统运行Linux。我写了一个快速程序 C
和 统计系统调用 显示 st_mtime
作为 truncate(xyz...000/1000)
.
更新: :我在Windows 7上使用NTF进行了相同的程序, 做 保持全毫秒的精度。这 MSDN链接 @MDMA提供了进一步的注意,即脂肪文件系统对于以10 ms分辨率的创建而准确,但访问仅准确至2秒。因此,这是真正的OS依赖性。
解决方案
文件系统不能精确存储时间,并且通常不会以毫秒的分辨率,例如FAT具有2秒钟的创建时间分辨率,而NTFS可以将最后一个访问时间延迟最多一个小时。 (详细信息 MSDN。
对于Jpoller的人们来说,这似乎是一个问题,因为这是处理逻辑所在的地方。在修复之前,您可以通过手动设置每个文件的最后一个修改时间为+4秒,从实际时间 - +4是一个任意值,应该比您正在处理的文件系统的分辨率大。当文件写入文件系统时,它们将被舍入,但要小于您添加的价值。不漂亮,但是它会起作用!
其他提示
最后修饰的时间戳显然是在几秒钟内存储的,而不是以毫秒为单位。这可能是文件系统限制。我建议将其与几秒钟而不是毫秒比较。
不隶属于 StackOverflow