How to implement a method to return Iterator files recursively in Java

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 be easily implemented using a keyword yield return. In Java, I suspect that I need to write a lot of complex code to do this. Is there a good solution to this problem?

Edit: I want the returned Iterator to be "lazy", i.e. returned a new file only when called next(). (This suggestion C # yield returnoffers.)

+5
source share
3 answers

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

+5
source

Apache Commons FileUtils iterator . , , .

.

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

.csv .

+3

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

0
source

All Articles