非递归的方法来获取目录中的所有文件及其在Java中的子目录 [英] Non-recursive way to get all files in a directory and its subdirectories in Java

查看:525
本文介绍了非递归的方法来获取目录中的所有文件及其在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"));

但是,我希望有一个非递归方式(也许是现有的API调用)这样做如果没有,这是最干净的方式吗?

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?

推荐答案

您可以随时使用迭代方法替换递归解决方案一个堆栈(用于DFS)或一个队列(对于BFS):

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 somedir / somedir2));

printFiles(new File("somedir/somedir2"));

这篇关于非递归的方法来获取目录中的所有文件及其在Java中的子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆