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

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -