Recursive file listing in java
It turns out that when you search on the web for “recursive file java” you only find horrible examples on how to implement directory traversal. It’s such a simple algorithm but I feel obliged to provide a better example to the world. In fact directory traversal can be very elegantly be hidden by using anonymous classes. You just need to extend the following class
public class FileTraversal {
public final void traverse( final File f ) throws IOException {
if (f.isDirectory()) {
onDirectory(f);
final File[] childs = f.listFiles();
for( File child : childs ) {
traverse(child);
}
return;
}
onFile(f);
}
public void onDirectory( final File d ) {
}
public void onFile( final File f ) {
}
}
and then you can locally override and implement the methods you need.
new FileTraversal() {
public void onFile( final File f ) {
System.out.println(f);
}
}.traverse(new File("somedir"));
This cleanly separates out the actual traversal. So simple!