What happens if the first file this code encounters is a dir. Why does it not ignore all other files in that dir (therefore obscuring the results)?
This is taken from How do I iterate through the files in a directory in Java?
I’m not trying to dispute that this code works but how does it account for above scenario ?
public static void main(String... args) {
File[] files = new File("C:/").listFiles();
showFiles(files);
}
public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getName());
}
}
}
It doesn’t ignore it because it’s just making another recursive call – the original call (with the collection of files from the top level) is still on the stack. It makes a new call with a new list of files, referenced by a new parameter called
filesin a new stack frame.So if there’s a directory structure of
c:/a/b/cyou’ll end up with a stack of:When the “deepest” call (the top of the stack) returns, the next stack frame will still know about any other files at the same level, and may well recurse again.