Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using the Files and Path API, write code that reads all lines of a large log file, counts lines containing ERROR, and does not load the whole file into memory.

We open the file with Files.lines(path, StandardCharsets.UTF_8) inside try-with-resources, filter the lines that contain ERROR and count them. Files.lines is lazy, so it reads the file a block at a time as the stream pulls lines, and memory stays small however large the file is; because it holds the file open, it must be closed. Files.readAllLines would load every line into a List and is unsuitable for large files, and malformed input for the charset shows up as an UncheckedIOException while the stream runs.

Why this question is asked

Counting matching lines in a log file is a small task, but it touches three things that matter whenever we process big inputs: memory, resource handling and character decoding. A version that works on a 2 MB test file can run out of heap on a 6 GB production log, leak a file handle in a scheduled job, or stop with a confusing exception on one bad byte. Interviewers ask it to see whether we reach for the streaming API and handle its edges. In this answer, we will write the solution, see why it is lazy and why it must be closed, compare it with readAllLines, and deal with charset errors.

1A Quick Recap of the Tools

Path represents a file location and Files is the class of static methods that operate on paths. Files.lines(path, charset) returns a Stream<String>, a pipeline of lines that we can transform with filter, map and terminal operations such as count. A stream is lazy: nothing is read until a terminal operation asks for elements, and then elements flow one at a time through the pipeline.

A charset is the rule for turning bytes into characters. Log files are almost always UTF-8, and we pass it explicitly so the code does not depend on the platform default.

2The Solution

Here is the complete method, followed by what happens when we run it on a large file.

Java
static long countErrors(Path path) throws IOException {
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
return lines.filter(l -> l.contains("ERROR")).count();
}
}
Path log = Path.of("/var/log/app/app.log"); // 6 GB, 40 million lines
System.out.println(countErrors(log)); // 18342
// Heap use during the run stays at a few MB, not 6 GB

Notice the three parts. try-with-resources makes sure the stream, and the file under it, is closed when the method returns or throws. filter keeps only lines that contain ERROR; contains is a plain substring check, which is what the task asks for, and a stricter check such as a regex for the log level column could replace it. count is the terminal operation that drives the reading.

3Why It Does Not Load the Whole File

Under the hood Files.lines uses a BufferedReader. When count asks for the next element, the stream asks the reader for the next line, the reader decodes bytes from its buffer, refilling the buffer from the file about 8 KB at a time, and the line goes through filter. If it matches, count increments a number; either way the line is then unreachable and the garbage collector can reclaim it. At any moment memory holds one buffer and the current line, so the program's footprint does not depend on the file size.

Step throughHow one line flows through the stream
  1. count() asks for the next line
  2. BufferedReader returns a linerefills its buffer from the file when empty
  3. Line contains ERROR?
    Yescount = count + 1Nodrop the line
  4. End of file?
    Yesreturn the count, close the fileNoask for the next line

4 steps in order. Play them, or step through them one at a time.

For very large files, Files.lines can also run in parallel with lines.parallel(), and for UTF-8 and some other charsets the JDK splits the file efficiently for that. For a simple count the disk is usually the bottleneck, so parallelism rarely helps much; measure before adding it.

4Why the Stream Must Be Closed

Most streams in Java, such as those from a List, hold no resources and need no closing. The stream from Files.lines is different: it holds an open file handle until it is closed, and reaching the end of the stream does not close it. Without try-with-resources, each call leaks one file descriptor. In a one-off program that hardly matters, but in a service or a scheduled job that calls this every minute, the process eventually hits its descriptor limit and fails with Too many open files, and on Windows an open file also blocks deleting or rotating it. The same rule applies to Files.list, Files.walk and Files.find.

5Why Not Files.readAllLines

Files.readAllLines(path, UTF_8) reads the whole file into a List<String> and returns it. For a small configuration file that is convenient. For our 6 GB log it would need far more than 6 GB of heap, because each line becomes a separate String object with its own header and array, and ASCII text in Java Strings takes one byte per character at best. The program would fail with OutOfMemoryError or spend most of its time in garbage collection. The same is true of Files.readString and Files.readAllBytes. So the rule is to use the read-everything methods only when the file is known to be small, and streams for anything that can grow.

Java
List<String> all = Files.readAllLines(log, StandardCharsets.UTF_8);
// java.lang.OutOfMemoryError: Java heap space (6 GB file, -Xmx2g)

6Handling Malformed Input

If the file contains bytes that are not valid UTF-8, for example because one component wrote a line in Windows-1252, the decoder fails. Files.lines decodes with a decoder that reports errors rather than replacing bad bytes. Because Stream methods cannot throw checked exceptions, the underlying MalformedInputException is wrapped in an UncheckedIOException, thrown in the middle of the stream processing, not when Files.lines is called.

Java
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
return lines.filter(l -> l.contains("ERROR")).count();
} catch (UncheckedIOException e) {
throw new IOException("cannot decode " + path + " as UTF-8", e.getCause());
}
// Lenient alternative: replace bad bytes instead of failing
CharsetDecoder lenient = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE);
try (BufferedReader r = new BufferedReader(new InputStreamReader(Files.newInputStream(path), lenient))) {
return r.lines().filter(l -> l.contains("ERROR")).count();
}

Which behaviour is right depends on the job. For counting errors in logs, replacing a corrupt byte with a replacement character is usually fine and keeps the count running. For importing financial data, failing loudly is safer.

7Follow-up questions

How would you count the errors per hour instead of in total?

We keep the same streaming structure and change the terminal operation. After filtering, we map each line to its hour, for example the first 13 characters of an ISO timestamp, and collect with Collectors.groupingBy(hour, TreeMap::new, Collectors.counting()). Memory then grows with the number of distinct hours, not with the number of lines.

Is a plain BufferedReader loop worse than Files.lines?

No. A while loop over readLine() on Files.newBufferedReader(path, UTF_8) has the same memory behaviour and avoids the stream machinery; it also throws plain IOException for malformed input. Files.lines is shorter and composes well with other stream operations; both are correct for large files.

8Conclusion

In this answer, we counted ERROR lines with Files.lines, filter and count inside try-with-resources. Files.lines reads lazily through a buffered reader, so memory stays small regardless of file size, but it holds the file open and must be closed. Files.readAllLines loads everything into memory and does not suit large files, and invalid bytes for the charset surface as an UncheckedIOException during processing, which we either report clearly or avoid with a lenient decoder.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write try, open Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8), and return lines.filter(l -> l.contains("ERROR")).count(). Files.lines is lazy: it is backed by a BufferedReader, and lines are only read as the count pulls them through the filter, so at any time the memory holds one buffer and one line, and a 6 GB log needs only a few megabytes.

Then, if they want more

Two details matter. First, the stream holds an open file handle and does not close itself at the end, so it has to be in try-with-resources; otherwise a job that runs this repeatedly leaks descriptors and eventually fails with Too many open files. Second, I pass the charset explicitly.

If the file contains bytes that are not valid UTF-8, the decoding error comes out as an UncheckedIOException in the middle of the stream, wrapping a MalformedInputException, so I would catch it and report which file failed, or, for logs, use a reader with a decoder that replaces malformed input.

What I would not use is Files.readAllLines, because it loads every line into a List and would run out of heap on a large file; the same goes for readString and readAllBytes. Those are fine only for files I know are small.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using the Files and Path API, write code that reads all lines of a large log file...": https://scrivio-interview-library.netlify.app/java/io-and-nio/ce0db4458b/