使用nio.file.DirectoryStream递归列出目录中的所有文件; [英] Recursively list all files within a directory using nio.file.DirectoryStream;

查看:1154
本文介绍了使用nio.file.DirectoryStream递归列出目录中的所有文件;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出指定目录中的所有文件和该目录中的子目录。不应列出目录。

I want to list all the FILES within the specified directory and subdirectories within that directory. No directories should be listed.

我目前的代码如下。它不能正常工作,因为它只列出指定目录中的文件和目录。

My current code is below. It does not work properly as it only lists the files and directories within the specified directory.

我该如何解决?

final List<Path> files = new ArrayList<>();

Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
try
{
  DirectoryStream<Path> stream;
  stream = Files.newDirectoryStream(path);
  for (Path entry : stream)
  {
    files.add(entry);
  }
  stream.close();
}
catch (IOException e)
{
  e.printStackTrace();
}

for (Path entry: files)
{
  System.out.println(entry.toString());
}

Regards。

推荐答案

Java 8提供了一个很好的方式:

Java 8 provides a nice way for that:

Files.walk(path)

此方法返回 Stream< Path>

这篇关于使用nio.file.DirectoryStream递归列出目录中的所有文件;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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