How do I use Files.walk() method to read directory contents?

The Files.walk() method in Java is a handy method when it comes to reading directory contents. Files.walk() method returns a Stream object that you can use to process each of the elements (files or directories) in the directory structure.

This method walks the file tree in a depth-first manner, starting from the given path that you provide as its parameter. It visits all files and directories in the file tree.

Here’s a simple example of how to use it. In this case, we are printing out the path to each file/directory.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FileWalkExample {
    public static void main(String[] args) {
        Path start = Paths.get("D:/Games");
        try (Stream<Path> stream = Files.walk(start)) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.walk() also supports a maximum depth argument, so you can limit how deep into the directory structure you want to go. For example, Files.walk(start, 2) would only go two levels deep.

Please note: You should always close the stream after you’re done with it to free up system resources. This is done automatically here with a try-with-resources statement.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.