Skip to content

Instantly share code, notes, and snippets.

@mrenouf
Created January 30, 2011 11:46
Show Gist options
  • Save mrenouf/802807 to your computer and use it in GitHub Desktop.
Save mrenouf/802807 to your computer and use it in GitHub Desktop.
Filesystem iterator, implemented with a stack instead of recursion. Returns only files.
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class Paths implements Iterable<File> {
private final File root;
private boolean returnFiles = true;
private boolean returnDirs = false;
public static Paths walk(File root) {
return new Paths(root);
}
public Paths(File root) {
this.root = root;
}
public Paths returnDirs(boolean value) {
this.returnDirs = value;
return this;
}
public Paths returnFiles(boolean value) {
this.returnFiles = value;
return this;
}
@Override
public Iterator<File> iterator() {
return new Iterator<File>() {
final List<Iterator<File>> dirStack = new ArrayList<Iterator<File>>();
Iterator<File> currentDir = Arrays.asList(root.listFiles()).iterator();
final boolean returnDirs = Paths.this.returnDirs;
final boolean returnFiles = Paths.this.returnFiles;
@Override
public boolean hasNext() {
return currentDir.hasNext();
}
@Override
public File next() {
while (currentDir.hasNext()) {
final File entry = currentDir.next();
if (entry.isDirectory()) {
final File[] entries = entry.listFiles();
if (entries.length > 0) {
dirStack.add(currentDir);
currentDir = Arrays.asList(entry.listFiles()).iterator();
if (returnDirs) {
return entry;
}
}
} else {
while (!currentDir.hasNext() && !dirStack.isEmpty()) {
currentDir = dirStack.remove(dirStack.size() - 1);
}
if (returnFiles) {
return entry;
}
}
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment