简体   繁体   中英

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).

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.

Files.walkFileTree() calls FileTreeWalker.walk(), which calls Files.newDirectoryStream(). The only explanation I can think of is that Files.newDirectoryStream returns a DirectoryStream that includes the deleted file.

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. The documentation for DirectoryStream says:

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.

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 .
  2. The file's type has a Windows Property Handler associated with it.
  3. Windows has time to start indexing the file before it is deleted.
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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