简体   繁体   中英

Using stack to make file/directory tree in Java

I need to return or print a file/directory tree using stack data structure. For example:

Folder1
    Folder1.1
        File1.1.1
    Folder1.2
Folder2
    File2.1
    File2.2
...

My code so far:

public static void filetree(File mainfolder, int indent){

    Stack<String> filesanddirectories = new Stack<>();

        for (File file : mainfolder.listFiles()){
            if (file.isDirectory()){
                filesanddirectories.push(file.getName());
                filetree(file, 0);
            }
            else if (file.isFile()){
                filesanddirectories.push(file.getName());
            }
        }

    for (int i = 0; i < filesanddirectories.size(); i++){
        System.out.println(filesanddirectories.pop());
    }
}

This code prints folders and files but with no indention, backwards and not exactly in the right order.

Could someone explain the logic of how it should work?

EDIT: Found a solution using recursion and stack (although stack seems to be unnecessary)

I used indent and temp variables to keep the indent when traversing recursively through the file directory. Then printed indent at the start of the for loop.

public static void filetree(File mainfolder, int indent) {

        int temp;

        for (File file : mainfolder.listFiles()) {
            for(int i = 0; i<indent; i++) {
                System.out.print("  ");
            }
            temp = indent;
            if (file.isDirectory()) {

                indent++;
                System.out.println(file.getName()); 

                filetree(file, indent);
                indent--;

            } else if (file.isFile()) {

                System.out.println(file.getName());
                indent = temp;
            } 
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM