[英]how to implement the hasNext method in sinlgly linkedlist iterator in java?
[英]How to implement a method to return Iterator of files recursively in Java
我想實現這樣的方法:
public Iterator<File> getFiles(String root) {
// return an Iterator looping through all files in root and all files in sub-directories of roots (recursively)
}
在C#中,可以使用yield return
關鍵字輕松實現。 在Java中,我懷疑我必須編寫大量復雜的代碼才能完成它。 這個問題有什么好的解決方案嗎?
編輯:我希望返回的迭代器是“懶惰的”,即只在調用next()
時返回一個新文件。 (這就是C# yield return
的行為。)
此代碼可能是您的解決方案http://snippets.dzone.com/posts/show/3532
Apache Commons FileUtils提供迭代器方法來遍歷目錄和子目錄。 這樣做你想要的,應該為你節省大量的工作。
例如
Iterator fi = iterateFiles(new File("."), String[] {".csv"}, true)
找到當前目錄下的所有.csv文件。
我可能錯過了一些東西,但為什么不只是創建自己的迭代器類來實現迭代器。 然后你只需要在迭代器中實現一個懶惰的next()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.