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

查看:27
本文介绍了在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("abc/def.ghi"));

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

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