Skip to main content

Breadth First FileVisitor?

4 replies [Last post]
Anonymous

I was looking over the NIO2 tutorial for walking a file tree at

http://download.oracle.com/javase/tutorial/essential/io/walk.html

Under the section "Considerations when Creating a FileVisitor" it mentions that a "file tree is walked depth first."

My question is, does or will JDK 7 provide an implementation for a breadth first file visitor behavior?

If not, maybe this functionality should be included. The value FileVisitOption.BREADTH_FIRST could be added to the existing FileVisitOption enum to override the depth first behavior in walking the tree.

Thoughts, pros, cons?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
alanb
Offline
Joined: 2005-08-08
Points: 0

It's depth first because that's the traversal order that you almost always want when doing recursive operations (cp, mv, chmod, rm, etc.). It shouldn't be too difficult for you to implement your own breath first if you really need it. It just means using DirectoryStream directly.

fudmail

The reason I ask this question is that, right or wrong, I unfortunately I have some JDK6 file system code that I'm looking to port and it happens to fall into the "almost never" category by using a breadth-first approach for its operation. I'd probably agree though, that for the file system operations you listed, I too would implement them using depth-first traversal.

It seems strange to me to provide a general purpose file tree walker capability and only provide support for depth first. As you suggested though, maybe depth-first is what is needed "most of the time."

rope74
Offline
Joined: 2011-02-01
Points: 0

Hi, just dropped in to say that the tool I made is also in the "almost never" category. I wanted to gather all the files in one directory to a List, do some magic, throw the List away, move to first subdirectory, put all the files into a List, and so forth. It would have been easier with the breadth-first traversal.
Just because cp, mv, etc. use depth-first does not automatically mean that it is always the Right Thing.
All I'm hoping for is options, so that someday someone just might invent something great.

alanb
Offline
Joined: 2005-08-08
Points: 0

You can do this yourself using a stack (an ArrayDeque would work well) and DirectoryStream. Pop a directory and then use DirectoryStream to visit all entries and just push any entries that are directories so that you'll visit them later. As was mentioned above, the walkFileTree method only currently does depth first search as that is what all the common file operations do. If you think BFS is importable then make the case on nio-dev.