Files Lines Read And Write

Process text files line by line with the NIO Files API, streaming through map and filter without loading the whole file into memory.

JavaData Fetching

Code

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

public class LogScan {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("app-", ".log");
        Files.write(log, List.of(
                "INFO boot ok",
                "ERROR db timeout",
                "INFO ready",
                "ERROR cache miss"));

        // lines():惰性流,逐行处理不整读
        List<String> errors = Files.lines(log)
                .filter(line -> line.startsWith("ERROR"))
                .map(line -> line.substring(6))
                .toList();
        System.out.println("errors = " + errors);

        // readAllLines:小文件可整读
        System.out.println("all lines = " + Files.readAllLines(log).size());
        Files.deleteIfExists(log);
    }
}

How it works

The snippet is organized around the class LogScan.

Applying it

The file announces its steps in the output: errors =, all lines =.

Output is labeled for readability — expect lines prefixed with errors =, all lines =.

Statements that matter

.filter(line -> line.startsWith("ERROR"))
.map(line -> line.substring(6))
.toList();

FAQ

What does Files Lines Read And Write print when run?
The script runs standalone; its 2 labeled outputs include `errors =`, `all lines =`.