java使用iterator遍历指定目录示例分享

时间:2022-03-10 21:20:26

可以遍历指定目录(一个或多个)及其所有子文件,用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);
  }
 }
}