Files Lines Lazy Large Log Scan

Scan a multi-gigabyte log line by line with Files.lines: lazy streaming, filtered early, and closed by try-with-resources without loading the file.

JavaResilience

Code

snippet
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class ErrorScanner {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("service-", ".log");
        Files.writeString(log, String.join("\n",
                "INFO boot ok",
                "ERROR disk 4 slow",
                "INFO retry queued",
                "ERROR disk 4 slow again"));

        // Files.lines 惰性逐行读:不会把整文件装进内存
        try (Stream<String> lines = Files.lines(log, StandardCharsets.UTF_8)) {
            long errors = lines
                    .filter(line -> line.startsWith("ERROR"))
                    .peek(line -> System.out.println("hit: " + line))
                    .count();
            System.out.println("error lines = " + errors);
        } // try-with-resources 关闭底层文件句柄

        Files.deleteIfExists(log);
    }
}

How the snippet works

Count the class ErrorScanner as the entire surface area of Files Lines Lazy Large Log Scan.

try-with-resources closes each declared resource automatically on every exit path.

Applying it

The demo output is labeled (hit:, error lines =), so every printed line maps back to its originating operation.

Statements that matter

.filter(line -> line.startsWith("ERROR"))
.peek(line -> System.out.println("hit: " + line))
.count();

Interactive Tools for This Topic

FAQ

What does Files Lines Lazy Large Log Scan print when run?
Invoke the file as-is — the `hit:`, `error lines =` prefixes identify which step printed each line.