Stackoverflowerror in recursive method when traversing folders and subfolders

Asked

Viewed 104 times

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;
    }

}

Gives the following error:

inserir a descrição da imagem aqui

What is going on?

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

1 answer

4


Your recursive method percorre() is being called always with the same parameters. This is causing the execution stack to burst (successive calls piled up and exceeded the maximum amount allowed).

I imagine you want to go through the subfolders. For this you must change this line:

percorre(caminho, espaço);

by that stretch:

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

I don’t know if that alone solves the problem because I don’t fully understand its logic. I don’t know what variables do espaço and nespaço. But the way to make the code work is this.

(Note: This excerpt else if (caminho.isDirectory() != true) may be replaced by a single else).

  • Thank you so much! It really worked. That was it!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.