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, Iterab...
可以遍历指定目录(一个或多个)及其所有子文件,用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, Iterable {
private Iterator iterator;
private List paths;
private List dirs;
public FileIterator(List paths) {
this.paths = new ArrayList(paths);
this.dirs = new ArrayList();
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 iterator() {
return this;
}
public static void main(String[] args) {
FileIterator iter = new FileIterator(Arrays.asList("."));
for (File file : iter) {
System.out.println(file);
}
}
}