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);
}
}
}
上一篇: 深入浅析hbase的优点