Java: Example - Recursive List
Here is an example of listing files and directories recursively.
// RecusiveList -- Recursively list directories and files
// Fred Swartz 1997-08-06 (Bangkok, Thailand)
// revised 2000-10-31 (Rota, Spain)
import java.util.*;
import java.io.*;
public class RecursiveList {
static final int maxDepth = 20; // max 20 levels (directory nesting)
static final String[] indent = new String[maxDepth]; // array of indents.
static final String indentString = " "; // single indent.
//===================================================================== main
public static void main(String[] args) {
indent[0] = indentString;
for (int i = 1; i < maxDepth; i++) {
indent[i] = indent[i-1] + indentString;
}
String root = (args.length>0) ? args[0] : System.getProperty("user.dir");
File start = new File(root);
if (start != null && start.isDirectory()) {
listDirContents(start, 0);
}else{
System.out.println("Not a directory: " + args[0]);
}
}//end main
//========================================================== listDirContents
public static void listDirContents(File someDirectory, int depth) {
if (depth > maxDepth) return;
String[] fileOrDirName = someDirectory.list(); // list of files and dirs
Arrays.sort(fileOrDirName);
for (int i = 0; i < fileOrDirName.length; i++) {
System.out.println(indent[depth] + fileOrDirName[i]); // print it
File f = new File(someDirectory, fileOrDirName[i]);
if (f.isDirectory()) {
listDirContents(f, depth+1); // Recursively list contents of dir
}
}
}//endmethod listDirContents
}//endclass