Files.list And Files.walk Must Be Closed

Files.list and Files.walk return DirectoryStream-backed streams that terminal ops never close; wrap every walk in try-with-resources or leak handles.

JavaResilience

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DirectoryStreamLeak {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("streams-");
        Files.writeString(dir.resolve("a.txt"), "1");
        Files.writeString(dir.resolve("b.txt"), "2");

        // count() 不会替你关流:Files.list 底层是打开的目录句柄,靠 GC 兜底
        long naive = Files.list(dir).count();
        System.out.println("naive count: " + naive);

        // 正确形态:try-with-resources 保证 DirectoryStream 在每个出口都关闭
        long safe;
        try (var entries = Files.list(dir)) {
            safe = entries.count();
        }
        System.out.println("safe count: " + safe);

        // Files.walk 同理:惰性遍历整棵树,同样必须显式关闭
        long regular;
        try (var tree = Files.walk(dir, 1)) {
            regular = tree.filter(Files::isRegularFile).count();
        }
        System.out.println("regular files: " + regular);

        Files.deleteIfExists(dir.resolve("a.txt"));
        Files.deleteIfExists(dir.resolve("b.txt"));
        Files.deleteIfExists(dir);
    }
}

The execution outline

Everything happens inside the class DirectoryStreamLeak.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Points of care

  • The toolchain you already have is enough to run it — nothing extra is needed.

Putting it to use

The run prints naive count:, safe count:, regular files: — each prefix names the step that produced it.

Core lines

regular = tree.filter(Files::isRegularFile).count();

Interactive Tools for This Topic

FAQ

What does Files.list And Files.walk Must Be Closed print when run?
Run it as a complete program — the output lines carry labels such as `naive count:`, `safe count:`, `regular files:`.