Friday, September 01, 2017

Directory Listing in Java

This post provides a examples of a few ways to list contents of a directory in Java. A couple of examples of how to recursively traverse a directory are also provided. Finally we will see the use of Files.walk() and Files.find() introduced in Java 8, which makes directory traversal even more simple.

List files using Files.list()

The simple Files.list() will list all files, including sub-directories. But will not go through listing sub-directories recursively.

List files using Files.list(), skipping sub-directories

We can use a filter() to filter out sub-directories and list only regular files

List files using DirectoryStream


Recursively List files in a directory using DirectoryStream

This example uses a recursive function to collect files in a directory and it's subdirectories into a list and print it.
public static void listFiles(Path path, List<Path> files) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
  for (Path file: stream) {
 if (Files.isDirectory(file)) {
   listFiles(file, files);
This method can be invoked as below
List<Path> files = new ArrayList<Path>();
listFiles(Paths.get("c:/test/"), files);

Recursively List files in a directory using Files.walkFileTree

Files.walkFileTree provides a simpler way than the above solution to traverse a directory and it's sub-directories. walkFileTree takes a FileVisitor as a parameter, for this example we will write a simple FileVisitor implementation which will add the files to a list.
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
 if (Files.isRegularFile(file)) {
 return FileVisitResult.CONTINUE;

Directory Traversal using Java 8 Files.walk() and Files.find()

Java 8 adds a couple of methods to the java.nio.file.Files that make recursive directory travesal much simpler. Files.walk() does a depth-first traversal of a directory, and can be used as below to process all files in a directory including the sub-directories.
Files.find() is also traverses the directory tree in depth-first manner, but also takes a BiPredicate as another parameter which is applied to each Path element encountered in the traversal.
Files.find(Paths.get("C:/test/"), Integer.MAX_VALUE, (filePath, attrs) -> attrs.isRegularFile()).forEach(System.out::println);


Popular Posts