Non-recursive way to get all files in a directory and its subdirectories in Java -
i trying list of files in directory , subdirectories. current recursive approach follows:
private void printfiles(file dir) { (file child : dir.listfiles()) { if (child.isdirectory()) { printfiles(child); } else if (child.isfile()) { system.out.println(child.getpath()); } } } printfiles(new file("somedir/somedir2"));
however, hoping there non-recursive way (an existing api call, maybe) of doing this. if not, cleanest way of doing this?
you can replace recursive solution iterative 1 using stack (for dfs) or queue (for bfs):
private void printfiles(file dir) { stack<file> stack = new stack<file>(); 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"));
Comments
Post a Comment