// Tyler Mi // Program that will print all the nested contents of a given file. // Note: This program works so well recursively because it takes // advantage of the fact that files are "recursive" structures. // "Files" are either "normal files" or "directories" which // contain "files". import java.io.*; import java.util.*; public class Crawler { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("directory or file name? "); String name = console.nextLine(); File f = new File(name); if (!f.exists()) { System.out.println("Does not exist"); } else { print(f); } } // Prints the file name, and if it is a directory, it will print out // all the nested contents with indentation public static void print(File file) { print(file, 0); } // Print the file name, and if it is a directory, it will print out // ALL of the nested contents with indentation. Level reperesents // how much space to print before the file name private static void print(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()) { print(subFile, level + 1); } } } // DO NOT TRY TO UNDERSTAND THIS CODE. This is the iterative, ugly, and hacky // way to iteratively approach this problem. public static void printIterative(File f) { Stack files = new Stack(); files.push(f); int level = 0; while(!files.isEmpty()) { File file = files.pop(); if (file != null) { for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(file.getName()); if (file.isDirectory()) { files.push(null); File[] subFiles = file.listFiles(); for (int i = subFiles.length - 1; i >= 0; i--) { files.push(subFiles[i]); } level++; } } else { level--; } } } }