Largest Files Under A Directory Tree

Stream the whole directory tree with Files.walk, sort by byte size, and keep only the top entries for disk usage triage.

JavaCli Tooling

Code

javasnippet
38 lines
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;

public class LargestFilesReport {

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("report-src");
        Files.writeString(root.resolve("notes.txt"), "x".repeat(5000));
        Files.writeString(root.resolve("tiny.log"), "hello");
        Path nested = Files.createDirectories(root.resolve("nested"));
        Files.writeString(nested.resolve("big.bin"), "y".repeat(12000));

        try (Stream<Path> stream = Files.walk(root)) {
            // walk the whole tree, keep the three largest entries by byte size
            stream.filter(Files::isRegularFile)
                  .sorted(Comparator.comparingLong(LargestFilesReport::sizeOf).reversed())
                  .limit(3)
                  .forEach(p -> {
                      try {
                          System.out.println(Files.size(p) + " bytes: " + root.relativize(p));
                      } catch (IOException e) {
                          throw new IllegalStateException(e);
                      }
                  });
        }
    }

    static long sizeOf(Path path) {
        try {
            return Files.size(path);
        } catch (IOException e) {
            return Long.MIN_VALUE;   // vanished files sort last
        }
    }
}

What the code does

One way to read it: the class LargestFilesReport and the function sizeOf, doing all the work.

The try-with-resources form guarantees each declared resource is closed even when the body throws. The failure path is explicit — IllegalStateException is raised when the guard condition holds.

Applying it

The entry-point signature is static long sizeOf(Path path)

The entry point wires sizeOf together — run it once and the whole demo flows.

Statements that matter

return Long.MIN_VALUE;   // vanished files sort last
}
throw new IllegalStateException(e);
return Files.size(path);

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
The code throws `IllegalStateException`. Handle it at the call site or let it propagate deliberately.
How do you run Largest Files Under A Directory Tree?
This is a complete program, not a library excerpt — execution starts at the top.