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("That file or directory does not exist"); } else { print(f); } }
// Prints the name of the given file. If the file is a directory, // recursively prints its content. Displays the name of each file // at the specified indentation level. // pre: f != null and f.exists() private static void print(File f, int indent) { for (int i = 0; i < indent; i++) { System.out.print(" "); } System.out.println(f.getName()); if (f.isDirectory()) { File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { print(files[i], indent + 1); } } }
// Prints the name of the given file. If the file is a directory, // recursively prints its content. The given file is printed at // 0 intendation. // pre: f != null and f.exists() public static void print(File f) { print(f, 0); }