Java Reference
In-Depth Information
if (f.isDirectory()) {
for (File subF : f.listFiles()) {
System.out.println(subF.getName());
if (subF.isDirectory()) {
// print contents of subdirectory
}
}
}
}
But even this won't work, because there might be directories within those inner
directories, and those directories might have subdirectories. There is no simple way
to solve this problem with standard iterative techniques.
The solution is to think recursively. You might be tempted to envision many differ-
ent cases: a file, a directory with files, a directory with subdirectories, a directory
with subdirectories that have subdirectories, and so on. However, there are really only
two cases to consider: Each object is either a file or a directory. If it's a file, we sim-
ply print its name. If it's a directory, we print its name and then print information
about every file and directory inside of it. How do we get the code to recursively
explore all of the possibilities? We call our own print method to process whatever
appears inside a directory:
public static void print(File f) {
System.out.println(f.getName());
if (f.isDirectory()) {
for (File subF : f.listFiles()) {
print(subF);
}
}
}
This version of the code recursively explores the structure. Each time the method
finds something inside a directory, it makes a recursive call that can handle either a
file or a directory; that recursive call might make yet another recursive call to handle
either a file or directory, and so on.
If we run this version of the method, we'll get output like the following:
homework
assignments.doc
hw1
Song.java
Song.class
hw2
DrawRocket.java
DrawRocket.class
Search WWH ::




Custom Search