Java Reference
In-Depth Information
The problem with this output is that it doesn't indicate the structure to us. We
know that the first line of output is the name of the starting directory ( homework ) and
that everything that follows is inside that directory, but we can't easily see the sub-
structure. It would be more convenient if the output used indentation to indicate the
inner structure, as in the following lines of output:
homework
assignments.doc
hw1
Song.java
Song.class
hw2
DrawRocket.java
DrawRocket.class
In this output we can more clearly see that the directory called homework contains
three elements, two of which are directories that have their own files ( hw1 and hw2 ).
We can get this output by including an extra parameter in the print method that
indicates the desired level of indentation. On the initial call in main , we can pass the
method an indentation of 0. On each recursive call, we can pass it a value one higher
than the current level. We can then use that parameter to print some extra spacing at
the beginning of the line to generate the indentation.
Here is our program, including the new version of the method with indentation:
1 // This program prompts the user for a file or directory name
2 // and shows a listing of all files and directories that can be
3 // reached from it (including subdirectories).
4
5 import java.io.*;
6 import java.util.*;
7
8 public class DirectoryCrawler {
9 public static void main(String[] args) {
10 Scanner console = new Scanner(System.in);
11 System.out.print("directory or file name?");
12 String name = console.nextLine();
13 File f = new File(name);
14 if (!f.exists()) {
15 System.out.println("No such file/directory");
16 } else {
17 print(f, 0);
18 }
19 }
20
Search WWH ::




Custom Search