Skip to content
Advertisement

Why Java Files.walkFileTree throw a NoSuchFileException?

I’m using Files.walkFileTree to delete a directory. When running this code in CentOS, I got an error in my server log.

JavaScript
JavaScript

I searched some keywords on the internet and there is no answer yet, maybe something is wrong with my code. So I wonder is it because Files.walkFileTree is not thread safe or something? I think maybe there is another thread changing the file here (maybe). Or maybe because of some thread is reading the files inside at that moment?

Advertisement

Answer

The Files.walkFileTree isn’t implementing a read-consistent view of the file system – that would be an unreasonable expectation. A scan might run for a significant length of time and it will be retrieving the latest contents of each particular directory traversal at any particular moment and not for the instant at which the scan began.

When it encounters an inconsistency in the items it has scanned – such as a file that was in some directory but deleted by some external thread or process – it correctly reports to the visitFileFailed callback. This is expected, just like new FileReader(file) would fail if another thread deletes the file moments before.

As you haven’t implemented visitFileFailed you get this default behaviour of SimpleFileVisitor – and therefore the stack trace you showed above:

JavaScript

Your own code can easily deal with this situation, as no such file is fine if you want to delete it anyhow:

JavaScript

Similarly a file could be deleted by another process or thread while you are receiving the visitFile(Path file, BasicFileAttributes attrs) callback so your own code needs to be defensive on the use of file and attrs, just as File.list() could return details of deleted files.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement