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 two “types” of directory: one with a * wildcard meaning it should also explore subdirectories and the classic one without wildcards that just get files present in that directory.
What I’m doing
Right 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 do not need to build a tree because I just need the files list so I was thinking maybe there’s a more efficient way to do it.
I was reading about the TreeModel but, as I understand it, it’s just an interface to implement a Jtree.
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.