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

前端 未结 3 2167
温柔的废话
温柔的废话 2020-12-14 10:55

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)          


        
3条回答
  •  悲哀的现实
    2020-12-14 11:23

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

提交回复
热议问题