Java Files find() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, Files.find(start, maxDepth, matcher) walks a directory tree like walk, but only returns paths for which your matcher returns true. The matcher is a BiPredicate<Path, BasicFileAttributes>, so it receives each path and its attributes.

Because the attributes are read during the walk anyway, checks such as attrs.isRegularFile() or attrs.size() cost nothing extra. Results come in no particular order, and the stream must be closed.

A static method of the final utility class java.nio.file.Files, available since Java 8. Call it on the class name, as in Files.find(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Start, depth limit, and a two-argument lambda:

Java
try (Stream<Path> hits = Files.find(root, Integer.MAX_VALUE,
        (path, attrs) -> attrs.isRegularFile() && path.toString().endsWith(".java"))) {
    hits.forEach(System.out::println);
}
CallWhat it does
(p, a) -> a.isRegularFile()Files only.
(p, a) -> a.size() > nFiles larger than n bytes.
(p, a) -> a.isDirectory()Folders, the start included.

Since Java 8. maxDepth is required; pass Integer.MAX_VALUE for no limit.

Library declarations
Java
public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options) throws IOException

Parameters

ParameterDescription
startWhere the search begins.
maxDepthMaximum number of levels to search.
matcherReturns true for paths to include.
optionsOptionally FOLLOW_LINKS.

Return Value

Return ValueDescription
Stream<Path>Matching paths, lazily, resolved against start.

Compare with Similar Methods

Related searches:

MethodHow it differs
walk()Same walk, filter with Stream.filter.
newDirectoryStream()Glob filter, one level only.
walkFileTree()Full control with a visitor.

Java Examples

Example 1 — Find All .java Files in a Project

Match regular files whose name ends in .java, at any depth.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FindJavaSources {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.createDirectories(dir.resolve("src"));
        Files.createDirectories(dir.resolve("test"));
        Files.write(dir.resolve("src/app.java"), new byte[0]);
        Files.write(dir.resolve("src/notes.txt"), new byte[0]);
        Files.write(dir.resolve("test/apptest.java"), new byte[0]);
        Files.write(dir.resolve("readme.md"), new byte[0]);
        List<String> sources;
        try (Stream<Path> hits = Files.find(dir, Integer.MAX_VALUE,
                (p, attrs) -> attrs.isRegularFile() && p.getFileName().toString().endsWith(".java"))) {
            sources = hits.map(p -> dir.relativize(p).toString().replace('\\', '/'))
                    .sorted()
                    .collect(Collectors.toList());
        }
        System.out.println("Java sources: " + sources);
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Four files, two matches. notes.txt and readme.md fail the name test; the two .java files pass.
  2. Attributes for free. attrs.isRegularFile() uses data the walk already read, so it is cheaper than calling Files.isRegularFile.
  3. Relative and sorted. Paths are made relative to the temp folder and sorted, since the search order is unspecified.

Example 2 — Find Files Larger Than 100 Bytes

Store the condition in a named BiPredicate and use attrs.size().

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FindBigFiles {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path archive = Files.createDirectory(dir.resolve("archive"));
        Files.write(dir.resolve("small.bin"), new byte[50]);
        Files.write(dir.resolve("big.bin"), new byte[200]);
        Files.write(archive.resolve("huge.bin"), new byte[500]);
        BiPredicate<Path, BasicFileAttributes> big = (p, attrs) -> attrs.isRegularFile() && attrs.size() > 100;
        List<String> found;
        try (Stream<Path> hits = Files.find(dir, Integer.MAX_VALUE, big)) {
            found = hits.map(p -> dir.relativize(p).toString().replace('\\', '/'))
                    .sorted()
                    .collect(Collectors.toList());
        }
        System.out.println("Over 100 bytes: " + found);
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Known sizes. The three files hold 50, 200, and 500 zero bytes.
  2. A reusable condition. Declaring the BiPredicate separately makes its two parameter types explicit and lets you pass it to several searches.
  3. Directories excluded. The archive folder is rejected by isRegularFile(), so only the two large files remain.

Example 3 — Find Folders Up to One or Two Levels Deep

Match directories with maxDepth 1 and then 2. The start folder matches too.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FindShallowFolders {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.createDirectories(dir.resolve("a/deep"));
        Files.createDirectories(dir.resolve("b"));
        for (int depth = 1; depth <= 2; depth++) {
            List<String> folders;
            try (Stream<Path> hits = Files.find(dir, depth, (p, attrs) -> attrs.isDirectory())) {
                folders = hits.map(p -> dir.relativize(p).toString().replace('\\', '/'))
                        .map(s -> s.isEmpty() ? "." : s)
                        .sorted()
                        .collect(Collectors.toList());
            }
            System.out.println("maxDepth " + depth + ": " + folders);
        }
        deleteTree(dir);
    }

    static void deleteTree(Path root) throws IOException {
        List<Path> all;
        try (Stream<Path> s = Files.walk(root)) {
            all = s.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
        for (Path p : all) {
            Files.delete(p);
        }
    }
}

How It Works

  1. Root counts. The start folder is a directory at depth 0, so it matches and is printed as a dot.
  2. One level. With maxDepth 1, a and b are found but a/deep is not reached.
  3. Two levels. Raising the limit to 2 adds a/deep, which sorts between a and b.

Frequently Asked Questions

Files.find(dir, Integer.MAX_VALUE, (p, a) -> a.isRegularFile() && p.toString().endsWith(".txt")), inside try-with-resources.
A function taking the Path and its BasicFileAttributes and returning true to include the path.
find gives you the attributes without another file system call, which is faster when you filter on size, type, or time.
Only if the matcher accepts it, for example a matcher that checks isDirectory().
In no particular order. Sort the stream for stable output.

Next: Files.getAttribute()

Read one file attribute by name, such as "basic:size" or "dos:hidden".

getAttribute() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful