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.)
This code might be your solution http://snippets.dzone.com/posts/show/3532
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With