Order of traversal in Files.walkFileTree

filesystems, java, java-7, java.nio.file

Solution

The order in which the subdirectories are read is not defined as per this comment in the Java Tutorial:

A file tree is walked depth first, but you cannot make any assumptions about the iteration order that subdirectories are visited.

As for the order in which the files are read, it depends (in the current implementation) on the supplied `DirectoryStream`, which is `sun.nio.fs.WindowsDirectoryStream` on my computer. Reading the javadoc of `DirectoryStream`, you will see that:

The elements returned by the iterator are in no specific order.

Problem

What is the order in which `Files.walkFileTree` visits files/directories at the same level? It doesn't appear to visit them in order of size, last modified time or name. I couldn't find anything in the API documentation either. Perhaps the `preVisitDirectory` method can be used to specify the order of visit but what is default behaviour ?

Original source