I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:
private void printFiles(File dir) {
for (File child : dir.listFiles()) {
if (child.isDirectory()) {
printFiles(child);
} else if (child.isFile()) {
System.out.println(child.getPath());
}
}
}
printFiles(new File("somedir/somedir2"));
However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?
解决方案
You can always replace a recursive solution with an iterative one by using a stack (for DFS) or a Queue (For BFS):
private void printFiles(File dir) {
Stack stack = new Stack();
stack.push(dir);
while(!stack.isEmpty()) {
File child = stack.pop();
if (child.isDirectory()) {
for(File f : child.listFiles()) stack.push(f);
} else if (child.isFile()) {
System.out.println(child.getPath());
}
}
}
printFiles(new File("somedir/somedir2"));