简体   繁体   中英

Non-recursive way to get all files in a directory and its subdirectories in Java

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<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("abc/def.ghi"));

Java 8 onward, you can use Files#walk to list out all files and directories recursively in a given directory. Further you can apply the filter like Files::isRegularFile to filter out the directories if you need only regular files.

On the flip side, if you only need to list the given directory but not its sub-directories, you can use the lazy method Files#list which will only give you the files and directories in the given directory. You can again further apply the filter mentioned above.

FileUtils Is probably the best way to go. (COPY OF THE LINKED QUESTION) only posted so people searching this will see it and will probably not read the comments

edit: Methods to be used Listfiles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM