0

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());
            }
        }
    }
Community
  • 1
  • 1
blue-sky
  • 51,962
  • 152
  • 427
  • 752

4 Answers4

2

When the first entry it encounters is a directory, it recursively calls showFiles() to work through the contents of that directory. When this call returns, the loop continues on with the entries from the first call to showFiles().

dty
  • 18,795
  • 6
  • 56
  • 82
1

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 files in a new stack frame.

So if there's a directory structure of c:/a/b/c you'll end up with a stack of:

showFiles([c:/a/b/c])
showFiles([c:/a/b])
showFiles([c:/a])
main(...)

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It just pushes another stack frame, when the recursive call finishes, it can resume where it previously left.

fortran
  • 74,053
  • 25
  • 135
  • 175
0

It works because the variable files is a local variable, i.e. there is one instance for each invocation of the method showFiles. This way all method executions are independent from one another and do not clobber their files variables.

Bombe
  • 81,643
  • 20
  • 123
  • 127