简体   繁体   English

是否可以在不存在的文件上调用Java的FileVisitor.visitFile()?

[英]Is it possible for Java's FileVisitor.visitFile() to be called on a nonexistent file?

Java's java.nio.file.Files.walkFileTree() executes the visitor's visitFile() method even if a file doesn't exist (a recently-deleted file). 即使文件不存在(最近删除的文件),Java的java.nio.file.Files.walkFileTree()也会执行访问者的visitFile()方法。

FileUtils.forceDelete(certainFile);
Files.exists(certainFile.toPath()); // Returns false, as expected
MySimpleFileVisitor visitor = new MySimpleFileVisitor(); // Extends SimpleFileVisitor. All it does is override visitFile() so I can see that it visits the deleted file.
Files.walkFileTree(directory, visitor); // Calls visitor.visitFile on certainFile. Not expected!

Is this possible? 这可能吗? I am using Windows, and the file is on a network drive. 我使用的是Windows,该文件位于网络驱动器上。

Files.walkFileTree() calls FileTreeWalker.walk(), which calls Files.newDirectoryStream(). Files.walkFileTree()调用FileTreeWalker.walk(),它调用Files.newDirectoryStream()。 The only explanation I can think of is that Files.newDirectoryStream returns a DirectoryStream that includes the deleted file. 我能想到的唯一解释是Files.newDirectoryStream返回包含已删除文件的DirectoryStream。

Yes, it is possible. 对的,这是可能的。

Let us assume that the Files.walk… methods all use DirectoryStreams to walk the file tree (which, at least as of Java 1.8.0_05, they in fact do) or an internal equivalent. 让我们假设Files.walk…方法都使用DirectoryStreams来遍历文件树(至少从Java 1.8.0_05开始,它们实际上是它们)或内部等价物。 The documentation for DirectoryStream says: DirectoryStream文档说:

The iterator is weakly consistent. 迭代器非常一致。 It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after the DirectoryStream is created. 它是线程安全的,但在迭代时不会冻结目录,因此它可能(或可能不)反映在创建DirectoryStream之后发生的目录的更新。

Yes, it is possible. 对的,这是可能的。 In my case, the following conditions had to be met to reproduce the failure: 就我而言,必须满足以下条件才能重现失败:

  1. The file of interest exists in a folder that is indexed by Windows . 感兴趣的文件存在于由Windows索引的文件夹中。
  2. The file's type has a Windows Property Handler associated with it. 该文件的类型具有与之关联的Windows属性处理程序。
  3. Windows has time to start indexing the file before it is deleted. Windows有时间在删除文件之前开始编制索引。
  4. The property handler takes a long time (a few minutes) to release its hold on the file. 属性处理程序需要很长时间(几分钟)来释放它对文件的保留。

I just discovered all of this information, which is why none of it is mentioned in the original question. 我刚刚发现了所有这些信息,这就是原始问题中没有提到它的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM