Video in progress

Strong Middle 📁 IO and NIO

You need to walk a directory with hundreds of thousands of files. Which do you pick: `Files.list`, `Files.walk` or `DirectoryStream`?

For a single level, DirectoryStream or Files.list: both are lazy. For recursive traversal, Files.walk, or Files.walkFileTree when you need filtering. File.listFiles() loads everything into an array at once.

📖 Answer

The old File.listFiles() reads the whole directory into a File[]. For 500 thousand files that means one big array and a slow response; and on an error it returns null with no reason.

The NIO.2 options:

// a single level, with a glob filter, lazy
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, "*.csv")) {
    for (Path p : ds) handle(p);
}

// recursive, limited depth
try (Stream<Path> s = Files.walk(root, 3)) {
    s.filter(Files::isRegularFile).forEach(this::handle);
}

Files.walk has a catch: if it reaches a directory you have no permission for, or a file disappears during the walk, it throws UncheckedIOException and the whole stream stops. On prod this happens often, especially in a directory where another process keeps moving files. In that case Files.walkFileTree is better: in visitFileFailed you log the error and return CONTINUE, and the walk goes on. With it you can also skip unneeded directories entirely using SKIP_SUBTREE.

Symlinks are not followed by default. If you pass FileVisitOption.FOLLOW_LINKS, the JDK detects cycles and throws FileSystemLoopException.

One more piece of advice: storing hundreds of thousands of files in one directory is a bad idea in itself, since lookups slow down on many file systems. It is better to split them into subdirectories by hash, like ab/cd/abcdef.jpg.