Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java 8 Find Files

Java 8 Find Files

In this tutorial you will learn how to find files using new Java NIO Files method that returns lazy and filtered stream of results.

In one of previous posts (Java List Files) you could read how to list directory files using old-school Java IO. Since Java 8 there is a new, very convenient Files.find() method that returns directory content as stream and takes two-argument function (BiPredicate<Path,BasicFileAttributes>) as a matcher. The matcher simply returns true/false to indicate whether a Path should be in resulting stream. Read how to work with BasicFileAttributes in post on Java File Metadata.

Remember that the stream is lazy, which means that the program won’t go through directory structure if you don’t take anything from the stream!

The find function takes optional 4th argument FileVisitOption, that allows to specify whether symlinks should be followed or not – by default not.

The code


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FindFilesExample {

    // Accepts search directory as parameter:
    public static void main(final String[] args) throws IOException {

        // Search in current directory or
        // the one given as program param:
        Path dir;
        if (args.length == 0) {
            dir = Paths.get(".");
        } else {
            dir = Paths.get(args[0]);

        System.out.printf("First 5 '.txt' files in %s:%n",

        try (Stream<Path> paths = Files.find(
                dir, Integer.MAX_VALUE,
                (path,attrs) -> attrs.isRegularFile()
                        && path.toString().endsWith(".txt"))) {
            // Consume only the first 5 from the stream:

We consume only the first 5 matching paths. This approach could be easily extended to implement, for example, paging of results using skip and limit.

Running the above program with /usr/share/doc as parameter gives the following result:

First 5 '.txt' files in /usr/share/doc:
Share with the World!