0Pricing
Java Academy · Lesson

Walking Directory Trees with Files.walk

Recursively list files, filter by extension, and compute directory sizes with Files.walk.

Walking Directory Trees with Files.walk is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Files.walk Overview

Files.walk(startPath) returns a lazy Stream<Path> that recursively lists all files and directories starting from the given path. Depth-first traversal, includes the start path itself.

import java.nio.file.*;
import java.util.stream.*;

try (Stream<Path> stream = Files.walk(Path.of("/home/user/projects"))) {
    stream.forEach(System.out::println);
} // stream and underlying resources closed automatically

Limiting Depth

Provide a max depth to prevent deep recursion:

Path root = Path.of("/home/user/projects");

// Only immediate children (depth 1)
try (var stream = Files.walk(root, 1)) {
    stream.filter(p -> !p.equals(root)) // exclude start path
          .forEach(System.out::println);
}

Filtering by File Type

Combine with Files.isRegularFile() or Files.isDirectory() to filter:

Path root = Path.of(".");

try (var stream = Files.walk(root)) {
    long fileCount = stream
        .filter(Files::isRegularFile)
        .count();
    System.out.println("Files: " + fileCount);
}

Filtering by Extension

Find all files with a specific extension:

try (var stream = Files.walk(Path.of("/src"))) {
    List<Path> javaFiles = stream
        .filter(Files::isRegularFile)
        .filter(p -> p.toString().endsWith(".java"))
        .collect(Collectors.toList());
    javaFiles.forEach(System.out::println);
}

Computing Directory Size

Sum all file sizes under a directory:

try (var stream = Files.walk(Path.of("/home/user/data"))) {
    long totalBytes = stream
        .filter(Files::isRegularFile)
        .mapToLong(p -> {
            try { return Files.size(p); }
            catch (IOException e) { return 0; }
        })
        .sum();
    System.out.printf("Total: %.2f MB%n", totalBytes / 1_048_576.0);
}

Files.list vs Files.walk

Files.list(dir) lists only the immediate contents of a single directory (like ls). Files.walk recurses into subdirectories.

// Only immediate children:
try (var stream = Files.list(Path.of("/home/user"))) {
    stream.forEach(System.out::println);
}

Files.find for Attribute-Based Search

Files.find(root, depth, matcher) is more efficient than walk+filter when matching on file attributes:

import java.nio.file.attribute.BasicFileAttributes;

try (var stream = Files.find(
        Path.of("/home/user"),
        Integer.MAX_VALUE,
        (p, attrs) -> attrs.isRegularFile() && attrs.size() > 1_000_000
)) {
    stream.forEach(p -> System.out.println("Large file: " + p));
}

Deleting a Directory Tree

Use walk + sorted(reversed) to delete a directory and all its contents (deepest files first):

Path toDelete = Path.of("/tmp/workdir");
try (var stream = Files.walk(toDelete)) {
    stream.sorted(Comparator.reverseOrder())
          .forEach(p -> {
              try { Files.delete(p); }
              catch (IOException e) { e.printStackTrace(); }
          });
}

Copying a Directory Tree

Walk the source tree and copy each file maintaining directory structure:

Path src = Path.of("/source"), dst = Path.of("/destination");
try (var stream = Files.walk(src)) {
    stream.forEach(p -> {
        try {
            Path target = dst.resolve(src.relativize(p));
            if (Files.isDirectory(p)) Files.createDirectories(target);
            else Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) { throw new RuntimeException(e); }
    });
}

Handling Inaccessible Files

Files.walk throws IOException if it encounters a directory it cannot read. Use FileVisitOption.FOLLOW_LINKS carefully — symlink loops can cause infinite recursion.

try (var stream = Files.walk(Path.of("/"),
        FileVisitOption.FOLLOW_LINKS)) { // caution: symlink loops
    // ...
} catch (IOException e) {
    System.err.println("Access error: " + e.getMessage());
}

walkFileTree: Event-Based Traversal

For finer control (pre-visit, post-visit, error handling), use Files.walkFileTree() with a FileVisitor:

Files.walkFileTree(Path.of("/home/user"), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("File: " + file);
        return FileVisitResult.CONTINUE;
    }
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("Dir: " + dir);
        return FileVisitResult.CONTINUE;
    }
});

Quick Check

Which Files method should you use to list ONLY the immediate children of a directory (no recursion)?

Recap: Files.walk

Key takeaways:

  • Files.walk(root) — recursive lazy Stream of all paths
  • Always use try-with-resources to close the stream
  • Filter by Files.isRegularFile/isDirectory; filter by extension with endsWith
  • Files.list(dir) — immediate children only
  • Files.find — efficient attribute-based search
  • walkFileTree — event-based with pre/post-visit callbacks

Frequently asked questions

Is the “Walking Directory Trees with Files.walk” lesson free?

Yes — the full text of “Walking Directory Trees with Files.walk” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Walking Directory Trees with Files.walk”?

Recursively list files, filter by extension, and compute directory sizes with Files.walk. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Walking Directory Trees with Files.walk” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Path: Representing File Locations
  2. Files Utility: Read, Write, Copy, Move
  3. Walking Directory Trees with Files.walk
  4. WatchService: Monitoring File Changes
← Back to Java Academy