Traversing directories without using recursion?

后端 未结 8 2068
无人及你
无人及你 2021-01-18 06:46

The Problem I need to write a simple software that, giving certain constraints, appends to a list a series of files. The user could choose between

8条回答
  •  独厮守ぢ
    2021-01-18 07:21

    Recursion can always be transformed into a loop.
    A quick and dirty possible solution (not tested) follows :

    private static void displayDirectory(File node){
        ArraList directories = new ArrayList();
        if (node.isDirectory())
           directories.append (node);    
        // Iterate over the directory list
        Iterator it = directories.iterator();
        while(it.hasNext()){
           File dir  = (File)it.next();           
           // get childs
           String[] subNote = dir.list();
           for(String filename : subNote){
              subNode = new File(node, filename);
              // display current child name
              System.out.println(subNode.getAbsoluteFile());
              // if directory : add current child to the list of dir to process
              if (subnode.isDirectory()){
                 directories.append(subNode);
              }
           }
        }
    }
    

    please note that the source node should be a directory for anything to be displayed.
    Also, this is a breadth-first display. if you want a depth first, you should change the "append" to put the file it just after the current node in the array list.

    i'm not sure about the memory consomation, however.
    Regards
    Guillaume

提交回复
热议问题