Skip to lesson

Large files with Files.lines

A server log can be many gigabytes, far more than a program's memory. Files.lines reads such a file as a stream, one line at a time, so you can filter, count and sum it with almost no memory.

Why readAllLines fails on huge files: OutOfMemoryError

OutOfMemoryError is the error Java throws when the heap, the memory where objects live, is full. readAllLines keeps every line of the file as a String in one list, so the whole file must fit in the heap at the same moment.

Example 1 · readAllLines keeps every line, even the ones you skip

AllInMemoryDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class AllInMemoryDemo {    public static void main(String[] args) throws IOException {        Path log = Path.of("server.log");        StringBuilder sb = new StringBuilder();        for (int i = 1; i <= 200_000; i++) {            if (i % 100_000 == 0) {                sb.append("ERROR order ").append(i).append(" failed\n");            } else {                sb.append("INFO order ").append(i).append(" paid\n");            }        }        Files.writeString(log, sb.toString());
        List<String> all = Files.readAllLines(log);        long chars = 0;        int errors = 0;        for (String line : all) {            chars += line.length();            if (line.startsWith("ERROR")) {                errors++;            }        }        System.out.println("Lines held in memory: " + all.size());        System.out.println("Characters held in memory: " + chars);        System.out.println("Lines we actually needed: " + errors);
        Files.delete(log);    }}
Output
Lines held in memory: 200000
Characters held in memory: 4288901
Lines we actually needed: 2

What this code does

  • To find 2 error lines, readAllLines built 200,000 String objects and kept all 4.3 million characters alive at once.
  • This file is about 4.5 MB, so it still works. The same code on a 4 GB log needs roughly 1,000 times more memory and stops with java.lang.OutOfMemoryError: Java heap space.

That is fine for a few megabytes. For a 4 GB log it fails with java.lang.OutOfMemoryError: Java heap space, even when you need only two lines of it. It is an Error, not an exception you should catch: the fix is to read differently.

Files.lines reads lazily

A lazy stream produces each element only when it is asked for. Files.lines is lazy: it reads the file one line at a time instead of loading all of it into memory.

Files.lines(path) returns a Stream<String> of the file's lines. It reads lazily: a line is read only when the stream pipeline asks for the next one, and earlier lines can be thrown away.

Example 2 · Files.lines reads only as far as it must

LazyLinesDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.Optional;import java.util.stream.Stream;
public class LazyLinesDemo {    public static void main(String[] args) throws IOException {        Path log = Path.of("gate.log");        StringBuilder sb = new StringBuilder();        for (int i = 1; i <= 50_000; i++) {            sb.append(i == 7 ? "ERROR gate 3 jammed" : "INFO entry " + i).append("\n");        }        Files.writeString(log, sb.toString());
        int[] looked = {0};        try (Stream<String> lines = Files.lines(log)) {            Optional<String> firstError = lines                    .peek(line -> looked[0]++)                    .filter(line -> line.startsWith("ERROR"))                    .findFirst();            System.out.println("First error: " + firstError.orElse("none"));        }        System.out.println("Lines looked at: " + looked[0] + " of 50000");
        Files.delete(log);    }}
Output
First error: ERROR gate 3 jammed
Lines looked at: 7 of 50000

What this code does

  • peek counts every line that reaches the pipeline. findFirst stops the stream at the first match, so only 7 lines were turned into Strings and checked.
  • Behind the scenes Java still reads the file in blocks of bytes, but it never holds more than a small part of it. Memory stays small whatever the file size.

Memory now stays small whatever the file size. If the pipeline stops early, as with findFirst or limit, the rest of the file is never read. Like the other Files methods it uses UTF-8 by default, and Files.lines(path, charset) takes a charset.

Closing the stream with try-with-resources

The stream from Files.lines keeps the file open until it is closed. A terminal operation such as count or toList finishes the stream but does not close it.

Example 3 · Closing the stream with try-with-resources

CloseLinesDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.stream.Stream;
public class CloseLinesDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("names.txt");        Files.writeString(file, "Asha\nRavi\nMeena\n");
        try (Stream<String> lines = Files.lines(file)                .onClose(() -> System.out.println("stream closed, file released"))) {            System.out.println("Lines: " + lines.count());        }        System.out.println("After the try block");
        // Mistake: no try-with-resources        Stream<String> leaky = Files.lines(file)                .onClose(() -> System.out.println("leaky stream closed only now"));        System.out.println("Leaky count: " + leaky.count());        System.out.println("The file is still open here");
        leaky.close(); // tidy up for the demo        Files.delete(file);    }}
Output
Lines: 3
stream closed, file released
After the try block
Leaky count: 3
The file is still open here
leaky stream closed only now

What this code does

  • onClose registers a small action that runs when the stream is closed. With try-with-resources it runs as soon as the block ends.
  • count() finishes the stream but does not close it. Without the close, the file stays open: a server that does this on every request runs out of file handles, and on Windows an open file cannot be deleted.

So always open it in try-with-resources: try (Stream<String> lines = Files.lines(path)) { ... }. A leaked stream keeps a file handle busy; a long-running server that leaks one per request ends up with "too many open files", and on Windows the file cannot be deleted while it is open.

filter, map and count on lines

A stream of lines works with every operation from the Streams section: filter to keep matching lines, map to split or parse them, count, sum, distinct, sorted and collect to finish. skip(1) drops a header line.

Example 4 · filter, map and count on a UPI log

UpiLogStatsDemo.javaJava
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.stream.Stream;
public class UpiLogStatsDemo {    public static void main(String[] args) throws IOException {        Path log = Path.of("upi.csv");        Files.writeString(log, """                date,payer,amount,status                2024-03-01,Asha,250,SUCCESS                2024-03-01,Ravi,1200,FAILED                2024-03-02,Meena,90,SUCCESS                2024-03-02,Asha,400,SUCCESS                2024-03-03,Kiran,75,FAILED                """, StandardCharsets.UTF_8);
        try (Stream<String> lines = Files.lines(log, StandardCharsets.UTF_8)) {            long failed = lines.skip(1).filter(line -> line.endsWith(",FAILED")).count();            System.out.println("Failed payments: " + failed);        }
        try (Stream<String> lines = Files.lines(log, StandardCharsets.UTF_8)) {            int received = lines.skip(1)                    .filter(line -> line.endsWith(",SUCCESS"))                    .map(line -> line.split(","))                    .mapToInt(parts -> Integer.parseInt(parts[2]))                    .sum();            System.out.println("Received: Rs " + received);        }
        try (Stream<String> lines = Files.lines(log, StandardCharsets.UTF_8)) {            List<String> payers = lines.skip(1)                    .map(line -> line.split(",")[1])                    .distinct()                    .sorted()                    .toList();            System.out.println("Payers: " + payers);        }
        Files.delete(log);    }}
Output
Failed payments: 2
Received: Rs 740
Payers: [Asha, Kiran, Meena, Ravi]

What this code does

  • skip(1) drops the header line. After that it is the same stream code you know from the Streams section, only fed from a file one line at a time.
  • A stream can be used once, so each question opens a fresh Files.lines in its own try block. For a really huge file, answer all questions in one pass instead (see the practice tab).

A stream can run only one terminal operation. For two answers, open the file twice in two try blocks, or collect both answers in one pass with groupingBy, which reads a huge file only once.

UncheckedIOException inside the stream

Errors while opening the file, such as NoSuchFileException, are thrown by Files.lines itself as normal checked exceptions. Errors while reading, such as bad bytes on line 5000, happen inside the terminal operation.

Example 5 · UncheckedIOException inside the stream

StreamErrorDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;import java.nio.charset.Charset;import java.nio.file.Files;import java.nio.file.Path;import java.util.stream.Stream;
public class StreamErrorDemo {    static void countLines(Path file) {        try (Stream<String> lines = Files.lines(file)) {            System.out.println(file + ": " + lines.count() + " lines");        } catch (UncheckedIOException e) {            System.out.println(file + ": failed while reading, cause " + e.getCause().getClass().getSimpleName());        } catch (IOException e) {            System.out.println(file + ": could not open, " + e.getClass().getSimpleName());        }    }
    public static void main(String[] args) throws IOException {        Path good = Path.of("good.txt");        Path bad = Path.of("bad.txt");        Files.writeString(good, "Asha\nRavi\n");        // line 2 was saved in windows-1252 by an old program        Files.writeString(bad, "Asha\nCafé bill\n", Charset.forName("windows-1252"));
        countLines(good);        countLines(bad);        countLines(Path.of("missing.txt"));
        Files.delete(good);        Files.delete(bad);    }}
Output
good.txt: 2 lines
bad.txt: failed while reading, cause MalformedInputException
missing.txt: could not open, NoSuchFileException

What this code does

  • Opening happens in Files.lines itself, so a missing file throws the checked NoSuchFileException right away.
  • Reading happens later, inside count(). Stream methods cannot throw checked exceptions, so the MalformedInputException arrives wrapped in an UncheckedIOException; getCause() gives back the real error.

Stream operations cannot throw checked exceptions, so Java wraps the IOException in UncheckedIOException. Catch it around the pipeline and call getCause() to see the real problem, for example MalformedInputException.

Catch UncheckedIOException first and IOException second; they are separate branches, so both catches are allowed.

Next step

Check your understanding

12 quick questions