Traversing files in a directory
In this recipe, we are going to explore how to traverse files in a given directory. We are going to obtain a FileTreeWalk class instance from a given File pointing to the directory. We are going to iterate through all the files inside the given directory, including any nested subdirectories. We will also filter the files to exclude those without the .txt extension and print their paths and contents to the console.
Getting ready
Make sure you have the sample files with the .txt extension included in your project. You can clone the sample project provided with the book at the GitHub repository: https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook. In this recipe, we are going to use the src/main/resources directory and its contents from the sample project.
How to do it...
- Import the
File.separatorconstant and assign an alias to it:
import java.io.File.separator as SEPARATOR
- Obtain the
FileTreeWalkinstance from theFilepointing to thesrc/main/resources...