// Program to print out all the files and subdirectories within // a given directory and all of its subdirectories. import java.util.*; import java.io.*; public class FileCrawler { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("File or directory name? "); String name = console.nextLine(); File file = new File(name); if (!file.exists()) { System.out.println("That file/directory does not exist."); } else { crawl(file); } } // pre: file points to a file or directory that exists // // list out all the files in the directory named by file and // all of its subdirectories, indented by depth public static void crawl(File file) { crawl(file, 0); } // pre: file points to a file or directory that exists // level >= 0 // // list out all the files in the directory named by file // if file is not a directory, just print its name // otherwise, print all files within the directory and all its // subdirectories, indenting to indicated depth private static void crawl(File file, int level) { for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(file.getName()); if (file.isDirectory()) { for (File subFile : file.listFiles()) { crawl(subFile, level + 1); } } } }