1 package com.quadcap.io; 2 3 40 41 import java.io.File ; 42 import java.io.FileFilter ; 43 44 import java.util.Iterator ; 45 import java.util.Stack ; 46 47 52 public class RecursiveFileIterator implements Iterator { 53 File root; 54 FileFilter filter; 55 Stack s = new Stack (); 56 File nextFile = null; 57 boolean done = false; 58 59 class IEntry { 60 File f; 61 File [] files; 62 int pos; 63 64 public IEntry(File f) { 65 this.f = f; 66 this.files = f.listFiles(); 67 if (files == null) files = new File [0]; 68 this.pos = 0; 69 } 70 } 71 72 public RecursiveFileIterator(File root, FileFilter filter) { 73 this.root = root; 74 this.filter = filter; 75 if (root.isDirectory()) s.push(new IEntry(root)); 76 } 77 78 public boolean hasNext() { 79 while (nextFile == null && !done) { 80 if (s.size() == 0) { 81 done = true; 82 } else { 83 IEntry ie = (IEntry)s.peek(); 84 if (ie.pos >= ie.files.length) { 85 s.pop(); 86 } else { 87 File f1 = ie.files[ie.pos++]; 88 if (f1.isDirectory()) { 89 s.push(new IEntry(f1)); 90 } else { 91 if (filter.accept(f1)) nextFile = f1; 92 } 93 } 94 } 95 } 96 return !done; 97 } 98 99 public Object next() { 100 if (nextFile == null && !done) { 101 hasNext(); 102 } 103 Object ret = nextFile; 104 nextFile = null; 105 return ret; 106 } 107 108 public void remove() { 109 throw new RuntimeException ("not implemented"); 110 } 111 112 } 113 | Popular Tags |