StackOverflowError in recursive method when traversing folders and subfolders

1

This recursive method:

public static void percorre(File caminho, String espaço){

    if(caminho.isDirectory()){
        for (int cta = 1; cta <= nespaço; cta++){
            buffer.append(espaço);
        }

        buffer.append(caminho.getName() + "\n");
        nespaço += 1;
        percorre(caminho, espaço);

    } else if (caminho.isDirectory() != true){
        nespaço = 0;
    }

}

It gives the following error:

What's happening?

Note: Line 14 is the If and 21 is the recursive call.

    
asked by anonymous 03.12.2015 / 15:23

1 answer

4

Your recursive method percorre() is always called with the same parameters. This is popping up the execution stack (successive calls have stacked and exceeded the maximum amount allowed).

I imagine you want to go through the subfolders. To do this you should change this line:

percorre(caminho, espaço);

By this stretch:

for (File subpasta: caminho.listFiles()) {
   percorre(subspasta, espaço);
}

I do not know if this solves the problem by itself because I did not fully understand its logic. I do not know what the variables espaço and nespaço do. But the way to make the code work is this.

(Note: This else if (caminho.isDirectory() != true) can be replaced by a simple else ).

    
03.12.2015 / 15:39