File Search in Java

File Search in Java: How to Search Files and Folders (2026)

File Search in Java: How to Search Files and Folders

Searching files and folders is a common task in desktop tools, build scripts, and admin utilities. Java gives you two ways to do it: the older File class with recursion, and the newer Files.walk() from NIO.2. This page shows both with working examples.

Method 1: Using Files.walk (modern approach)

This is the recommended way. It is concise, uses streams, and handles deep directory trees cleanly.

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

public class FileSearch {

    public static void main(String[] args) throws IOException {

        Path start = Paths.get("C:/projects");
        String targetName = "application.properties";

        try (Stream<Path> stream = Files.walk(start)) {
            List<Path> matches = stream
                    .filter(Files::isRegularFile)
                    .filter(p -> p.getFileName().toString().equals(targetName))
                    .collect(Collectors.toList());

            for (Path p : matches) {
                System.out.println(p);
            }
        }
    }
}

Output: Every full path where application.properties exists under C:/projects.

Method 2: Using the File class with recursion (older approach)

Use this only if you are on legacy code that predates Java 7. For new code, use Files.walk().

import java.io.File;

public class FileSearchOld {

    public static void search(File folder, String targetName) {
        File[] files = folder.listFiles();
        if (files == null) return;

        for (File f : files) {
            if (f.isDirectory()) {
                search(f, targetName);
            } else if (f.getName().equals(targetName)) {
                System.out.println(f.getAbsolutePath());
            }
        }
    }

    public static void main(String[] args) {
        File root = new File("C:/projects");
        search(root, "application.properties");
    }
}

Output: Same result, but written with older Java APIs.

Searching by extension instead of exact name

Most real use cases need "find all .log files" rather than a single exact name. Change the filter:

List<Path> logs = stream
        .filter(Files::isRegularFile)
        .filter(p -> p.getFileName().toString().endsWith(".log"))
        .collect(Collectors.toList());

Searching by file size

Files.walk() returns Path objects. Use Files.size(path) inside the filter to find files larger than a threshold:

List<Path> largeFiles = stream
        .filter(Files::isRegularFile)
        .filter(p -> {
            try {
                return Files.size(p) > 10 * 1024 * 1024; // 10 MB
            } catch (IOException e) {
                return false;
            }
        })
        .collect(Collectors.toList());

Searching by modified date

Use Files.getLastModifiedTime(path) to filter files modified after a given timestamp:

Instant cutoff = Instant.now().minus(7, ChronoUnit.DAYS);

List<Path> recent = stream
        .filter(Files::isRegularFile)
        .filter(p -> {
            try {
                return Files.getLastModifiedTime(p).toInstant().isAfter(cutoff);
            } catch (IOException e) {
                return false;
            }
        })
        .collect(Collectors.toList());

Common errors and how to fix them

Error Cause Fix
NoSuchFileException The starting path does not exist. Check the path. Use Files.exists(Paths.get(...)) before walking.
AccessDeniedException The process lacks read permission on some folder. Catch the exception in the stream or skip inaccessible directories.
StackOverflowError (recursive File approach) Very deep directory tree hits the recursion limit. Use Files.walk(), which is iterative and does not use stack frames.
Unhandled IOException Forgetting to wrap Files.walk() in a try block. Use try-with-resources around the stream.

Where to go next

You now know how to search files and folders in Java with both the old File class and the modern Files.walk() API.

If you remember one thing, remember this: use Files.walk() for new code. It is safer, shorter, and handles deep trees without stack overflow.

If you want to go deeper, try these next steps:

  • Add a filter for file extension and run it on a real project directory.
  • Try searching for files modified in the last 24 hours. Use Files.getLastModifiedTime().
  • Wrap the stream in parallel() and compare speed on a large folder. Watch out for permission exceptions in parallel mode.
  • Move on to WatchService. It lets you watch a folder and react to files being created, modified, or deleted in real time.

No comments: