Recursively list all files within a directory using nio.file.DirectoryStream;

Danny Rancher picture Danny Rancher · Jan 8, 2014 · Viewed 78.9k times · Source

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.

How can I fix this?

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());
}

Answer

Vladimir Petrakovich picture Vladimir Petrakovich · Apr 23, 2016

Java 8 provides a nice way for that:

Files.walk(path)

This method returns Stream<Path>.