Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

iterator

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.)

like image 362
Buu Nguyen Avatar asked Apr 24 '09 09:04

Buu Nguyen


2 Answers

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

like image 198
Pierre Avatar answered Nov 14 '22 23:11

Pierre


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.

like image 43
Brian Agnew Avatar answered Nov 14 '22 23:11

Brian Agnew