tags:

views:

820

answers:

3

I want to implement a method like this:

public Iterator<File> getFiles(String root) {
  // return an Iterator looping through all files in root and all files in sub-directories of roots (recursively)
}

In C#, this can easily be implemented with the yield return keyword. In Java, I suspect I have to end up writing a lot of complicated code to get it done. Is there any good solution to this problem?

Edit: I want the returned Iterator to be "lazy", i.e. only return a new File when next() is invoked. (That is the behavior C#'s yield return offers.)

+3  A: 

Apache Commons FileUtils offers iterator methods to iterate through directories and subdirectories. That does what you want and should save you a lot of work.

e.g.

Iterator fi = iterateFiles(new File("."), String[] {".csv"}, true)

to find all .csv files below the current directory.

Brian Agnew
As I look into the source code, it turns out that the code adds all files into a collection and finally calls iterator() method on that collection. I want a lazy, not eager-loading Iterator. I have updated the original post. Thanks for bringing this up anyway, will come very handy in other occasions.
Buu Nguyen
Ok. In that case I think you may need a recursive method and provide your own callback object. I don't of any off the top of my head, unfortunately.
Brian Agnew
+4  A: 

This code might be your solution http://snippets.dzone.com/posts/show/3532

Pierre
A: 

I might have missed something, but why don't you just make your own iterator class which implements iterator. Then you just need to implement a lazy next() method in you iterator.

Martin Tilsted
Sure that's something I would do unless somebody already solved that problem in smarter ways that I could possibly come up with. And this answer seems to suggest 1 of such solutions http://stackoverflow.com/questions/785228/how-to-implement-a-method-to-return-iterator-of-files-recursively-in-java/785236#785236
Buu Nguyen