Java – does not use recursion to traverse directories?

problem

What am I doing

Now I'm doing the stupidest thing:

import java.io.File;

public class Eseguibile {

    private static void displayIt(File node){

        System.out.println(node.getAbsoluteFile());

        if(node.isDirectory()){
            String[] subNote = node.list();
            for(String filename : subNote){
                displayIt(new File(node,filename));
            }
        }
    }

    public static void main(String[] args){
        System.out.println("Ciao");

        displayIt( new File("/home/dierre/") );

    }

}

I don't need to build a tree because I only need a file list, so I think there may be a more effective method

I'm reading about treemodel, but as far as I know, it's just an interface to implement JTree

Solution

Recursion is neither "stupid" nor necessarily inefficient In fact, in this particular case, recursive solutions may be more effective than non - recursive solutions Of course, recursive solutions are easier to code and understand than alternatives

The only potential problem with recursion is that if the directory tree is pathologically deep, you may overflow the stack

If you really want to avoid recursion, the natural way is to use the "file list stack" data structure You will recurse everywhere, push the list of file objects containing the current directory (remaining) onto the stack, read the new directory and start processing them Then, when you are finished, pop up the stack and continue to the parent directory This will give you depth first traversal For breadth first traversal, use the file queue data structure instead of the stack

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>