-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectoryCrawler.java
More file actions
51 lines (45 loc) · 1.64 KB
/
Copy pathDirectoryCrawler.java
File metadata and controls
51 lines (45 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* DirectoryCrawler.java - based closely on an example program from
* Chapter 12 of Reges & Stepp.
*
* Recursively prints the contents of a folder/directory -- including
* the contents of any subdirectories, their subdirectories, etc.
*/
import java.io.*;
import java.util.*;
public class DirectoryCrawler {
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("no such file/directory");
} else {
print(f); // print the file or directory
}
}
/*
* print - a recursive method for printing a file or directory
*
* The parameter f is a File object representing the file or directory.
*
* If f is a regular file, the method prints its name and returns.
* That is the base case of the method.
*
* If f is a directory, the method prints its name and then invokes
* the method recursively on all of the contents of the directory;
*/
public static void print(File f) {
System.out.println(f.getPath());
// If f represents a directory, recursively print its contents.
if (f.isDirectory()) {
File[] contents = f.listFiles();
for (int i = 0; i < contents.length; i++) {
print(contents[i]);
}
}
// Note: if f is NOT a directory, we've hit a base case
// and will just return.
}
}