forked from uclid/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursiveDirectory.java
More file actions
62 lines (50 loc) · 2.03 KB
/
RecursiveDirectory.java
File metadata and controls
62 lines (50 loc) · 2.03 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
52
53
54
55
56
57
58
59
60
61
62
import java.io.File;
import java.util.Scanner;
/**
* This program will list all the files in a directory
* and all its sub-directories, to any level of nesting
*/
public class RecursiveDirectory {
public static void main(String[] args) {
String directoryName; // Directory name entered by the user.
File directory; // File object referring to the directory.
Scanner scanner; // For reading a line of input from the user.
scanner = new Scanner(System.in); // scanner reads from standard input.
System.out.print("Enter a directory name: ");
directoryName = scanner.nextLine().trim();
directory = new File(directoryName);
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
}
else {
// Display the files of the directory recursively
listDirectoryContents(directory,"");
}
scanner.close();
} // end main()
/**
* It is a recursive subroutine that lists
* contents of a directory and its sub-directories
* to any level of nesting.
* @param dir the directory whose contents should be listed
* @param indent a string for indentation for each new level
* of directory
*/
private static void listDirectoryContents(File dir, String indent) {
String[] files; // names of files in the directory.
System.out.println(indent + "Directory \"" + dir.getName() + "\":");
indent += " "; // Increase the indentation for new level of recursion
files = dir.list();
for (int i = 0; i < files.length; i++) {
// If it is a directory, recursively list its contents
File f = new File(dir, files[i]);
if (f.isDirectory())
listDirectoryContents(f, indent);
else
System.out.println(indent + files[i]);
}
} // end listContents()
} // end class RecursiveDirectory