1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
package org.progx.io;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FileTreeWalker {
private File path;
private static final FileFilter directoryFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
};
private FileFilter filter;
public FileTreeWalker(File path) throws IOException {
this(path, new FileFilter() {
public boolean accept(File pathname) {
return pathname.isFile();
}
});
}
public FileTreeWalker(File path, FileFilter filter) throws IOException {
if (path == null || !path.exists() || path.isFile()) {
throw new IOException("Path " + path + " is not a valid directory.");
}
this.path = path;
this.filter = filter;
}
public void walk(FileTreeWalk walk) {
walkDirectory(walk, path);
}
private void walkDirectory(FileTreeWalk walk, File dir) {
File[] files = dir.listFiles(filter);
for (File file: files) {
walk.walk(file);
}
File[] dirs = dir.listFiles(directoryFilter);
for (File subDir: dirs) {
walkDirectory(walk, subDir);
}
}
} |
Partager