tags:

views:

106

answers:

3
A: 

If you choose to use recursion, I found an example that may be close to the one you are currently using as to eliminate any ambiguity .

// Process only directories under dir
public static void visitAllDirs(File dir) {
    if (dir.isDirectory()) {
        process(dir);

        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            visitAllDirs(new File(dir, children[i]));
        }
    }
}

This is a very simple example, the process() can be where you do your handling or operations on the directory.

etbal
source :http://www.exampledepot.com/egs/java.io/TraverseTree.html
org.life.java
+1  A: 

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

PATRY
+5  A: 

Right now I'm doing the stupidest thing ...

Recursion is neither "stupid" or necessarily inefficient. Indeed in this particular case, a recursive solution is likely to be more efficient than a non-recursive one. And of course, the recursive solution is easier to code and to understand than the alternatives.

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

If you really want to avoid recursion, then the natural way to do it is to use a "stack of list of File" data structure. Each place where you would have recursed, you push the list containing the current directory's (remaining) File objects onto the stack, read the new directory and start working on them. Then when you are finished, pop the stack and continue with the parent directory. This will give you a depth-first traversal. If you want a breadth-first traversal, use a "queue of File" data structure instead of a stack.

Stephen C
Stupid meaning the first thing I thought to do. Without deeper analisys.
dierre
Instinctive solutions are not necessarily stupid either :-)
Stephen C