Display tree-like directories

2

I have this code here in JAVA where I need to list the folders and subfolders in tree format, but I can not get it. Any help?

package Control;

import java.awt.Desktop;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PercorreDir {


    public static StringBuffer buffer = new StringBuffer();

    public static int nespaço = 1;
    public static String espaço = "";

    public static StringBuffer percorre(File caminho){

        if(caminho.isDirectory()){

            buffer.append(espaço + caminho.getName()+"\n");

            for (File subpasta: caminho.listFiles()) {          

                for (int cta = 0; cta < nespaço; cta++){
                    espaço += "    ";
                }

                nespaço += 1;

                percorre(subpasta);
                }
        } else {
            nespaço = 0;
            espaço = "    ";

        }

        return buffer;

    }
}
    
asked by anonymous 03.12.2015 / 23:39

1 answer

2

If problem is that whenever you find a file you "reset" the number of spaces to zero, which causes the next folder in the queue to print as if it were in the root. There is no need to do anything special in the case of files (since you do not want to treat them), instead I suggest incrementing the number of spaces before going through the subfolder, and finally decreasing again. Or better yet, do not use a global variable (static), but pass the prefix of each folder as a parameter:

public static StringBuffer percorre(File caminho){
    return percorre(caminho, "");
}

public static StringBuffer percorre(File caminho, String prefixo){

    if(caminho.isDirectory()){

        buffer.append(prefixo + caminho.getName()+"\n");

        String novoPrefixo = prefixo + "    ";

        for (File subpasta: caminho.listFiles()) {          
            percorre(subpasta, novoPrefixo);
        }
    }

    return buffer;

}
    
03.12.2015 / 23:47