java應用iterator遍歷指定目次示例分享。本站提示廣大學習愛好者:(java應用iterator遍歷指定目次示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是java應用iterator遍歷指定目次示例分享正文
可以遍歷指定目次(一個或多個)及其一切子文件,用Iterator完成
package archiver.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class FileIterator implements Iterator<File>, Iterable<File> {
private Iterator<String> iterator;
private List<String> paths;
private List<File> dirs;
public FileIterator(List<String> paths) {
this.paths = new ArrayList<String>(paths);
this.dirs = new ArrayList<File>();
this.iterator = this.paths.iterator();
}
public File next() {
File file = null;
if (hasNext()) {
file = new File(iterator.next());
if (file.isDirectory()) {
dirs.add(file);
}
}
return file;
}
public boolean hasNext() {
if (!iterator.hasNext()) {
paths.clear();
for (File dir : dirs) {
for (String name : dir.list()) {
paths.add(dir.getPath()+File.separator+name);
}
}
dirs.clear();
if (paths.size() == 0) {
return false;
}
iterator = paths.iterator();
}
return true;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<File> iterator() {
return this;
}
public static void main(String[] args) {
FileIterator iter = new FileIterator(Arrays.asList("."));
for (File file : iter) {
System.out.println(file);
}
}
}