如何实现一个方法在Java中递归返回文件的迭代器

Buu*_*yen 5 java iterator

我想实现这样的方法:

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

在C#中,可以使用yield return关键字轻松实现.在Java中,我怀疑我必须编写大量复杂的代码才能完成它.这个问题有什么好的解决方案吗?

编辑:我希望返回的迭代器是"懒惰的",即只在next()调用时返回一个新的文件.(这是C#yield return提供的行为.)

Pie*_*rre 5

此代码可能是您的解决方案http://snippets.dzone.com/posts/show/3532