This post will discuss how to traverse a directory to “recursively” list all files in Kotlin.

There are several ways to traverse a directory and list out all files present in it (and its subdirectories):

1. Using Files.walk() function

The Files.walk() function takes the root directory and returns a Stream<Path> by walking the file tree recursively in a depth-first manner. After getting the Stream, you can apply a filter on it to list only regular files.

Download Code

 
The above code fails to close the stream’s open directories after the stream’s operations have been completed. This function must be used within a use control structure to ensure that all resources are closed promptly. Here’s how the code would look like:

Download Code

 
Here’s an equivalent solution using the Files.find() function, which walks the file tree similar to the Files.walk() function.

Download Code

2. Using Files.walkFileTree() function

Alternatively, you can use the Files.walkFileTree() function to walk a file tree. It requires the root directory and an instance of the file visitor to invoke for each file.

Download Code

That’s all about traversing a directory to recursively list all files in Kotlin.