// CSE 143, Winter 2009, Marty Stepp // This program contains a recursive file/directory-crawling method. import java.io.*; // for File import java.util.*; // for Scanner public class FileCrawler { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Directory to crawl? "); String directoryName = console.nextLine(); File f = new File(directoryName); crawl(f); } // Prints the given file/directory and any files/directories inside it. // Precondition: f != null // "public / private pair" // public version: has the parameter(s) that the clients want to pass public static void crawl(File f) { crawl(f, 0); } // private version: has the parameter(s) that the coder needs in order to // implement the desired recursive behavior private static void crawl(File f, int indent) { for (int i = 0; i < indent; i++) { System.out.print(" "); } System.out.println(f.getName()); if (f.isDirectory()) { // recursive case (a directory) // print this directory's name, indented for (int i = 0; i < indent; i++) { System.out.print(" "); } System.out.println(f.getName()); // print all the files in this directory, recursively File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { crawl(files[i], indent + 4); } } } }