Java Files lines() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, Files.lines(path) returns a Stream<String> that reads the file lazily: a line is read only when the stream needs it. That keeps memory low even for very large files, and lets you stop early with limit or findFirst.

The stream holds the file open until it is closed, so always put it in a try-with-resources block. It decodes UTF-8 by default; an overload takes a Charset.

A static method of the final utility class java.nio.file.Files, available since Java 8. Call it on the class name, as in Files.lines(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Open the stream in a try-with-resources header:

Java
try (Stream<String> lines = Files.lines(log)) {
    long errors = lines.filter(l -> l.contains("ERROR")).count();
}
CallWhat it does
Files.lines(p)Lazy stream of lines, UTF-8.
Files.lines(p, cs)Same, decoding with charset cs.
Files.readAllLines(p)Eager: every line in a list at once.

Since Java 8. Line terminators are removed, exactly as with readAllLines.

Library declarations
Java
public static Stream<String> lines(Path path) throws IOException
public static Stream<String> lines(Path path, Charset cs) throws IOException

Parameters

ParameterDescription
pathThe text file to read.
cs(Second overload) Charset for decoding.

Return Value

Return ValueDescription
Stream<String>A lazily populated stream of lines; closing it closes the file.

Compare with Similar Methods

Line-reading options:

MethodHow it differs
readAllLines()Simpler for small files; no closing needed.
newBufferedReader()Classic loop with readLine().
readString()Whole file as one string (Java 11).

Java Examples

Example 1 — Count ERROR Lines in a Log

Stream the lines, keep those containing ERROR, and count them.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Stream;

public class LinesCountErrors {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path log = dir.resolve("app.log");
        Files.write(log, Arrays.asList("INFO start", "ERROR disk full", "INFO retry", "ERROR timeout", "INFO done"));
        long errors;
        try (Stream<String> lines = Files.lines(log)) {
            errors = lines.filter(l -> l.startsWith("ERROR")).count();
        }
        System.out.println("ERROR lines: " + errors);
        Files.delete(log);
        Files.delete(dir);
    }
}

How It Works

  1. Five log lines. Two of them begin with ERROR.
  2. Read as you go. The filter sees each line once and only the count is kept, so a huge log would not need much memory.
  3. Closed automatically. Leaving the try block closes the stream and the file, even if the filter had thrown.

Example 2 — Read Only the First Two Lines

limit(2) stops the stream after two lines; the rest of the file is never needed.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LinesFirstTwo {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path book = dir.resolve("book.txt");
        Files.write(book, Arrays.asList("Chapter 1", "It was a dark night.", "Chapter 2", "Morning came."));
        List<String> preview;
        try (Stream<String> lines = Files.lines(book)) {
            preview = lines.limit(2).collect(Collectors.toList());
        }
        System.out.println("Preview: " + preview);
        System.out.println("Preview size: " + preview.size());
        Files.delete(book);
        Files.delete(dir);
    }
}

How It Works

  1. A short-circuiting step. limit(2) asks for just two elements, and the stream stops pulling lines after that.
  2. Collect what you need. The two lines are copied into a list before the try block closes the stream.
  3. Why it matters. For a multi-gigabyte file this reads a few bytes instead of the whole file, which readAllLines cannot do.

Example 3 — Invalid UTF-8 Arrives as UncheckedIOException

A file with a byte that is not valid UTF-8 fails while the stream is being consumed.

Java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class LinesMalformed {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path bad = dir.resolve("bad.txt");
        Files.write(bad, new byte[] {'o', 'k', '\n', (byte) 0xFF, '\n'});
        try (Stream<String> lines = Files.lines(bad)) {
            System.out.println("Lines: " + lines.count());
        } catch (UncheckedIOException e) {
            System.out.println("Failed while reading: " + e.getCause().getClass().getSimpleName());
        }
        Files.delete(bad);
        Files.delete(dir);
    }
}

How It Works

  1. One bad byte. 0xFF never appears in valid UTF-8, so decoding the file must fail.
  2. The stream opens fine. Files.lines itself succeeds; the problem is only found when count() starts reading.
  3. Wrapped exception. The checked MalformedInputException is wrapped in an UncheckedIOException; getCause() reveals the original.

Frequently Asked Questions

Yes. It keeps the file open until closed. Use try (Stream<String> s = Files.lines(path)) { ... }.
lines returns a lazy Stream that reads as needed and must be closed; readAllLines reads everything into a List at once.
Reading happens inside stream operations, which cannot throw checked exceptions, so I/O errors during reading are wrapped in UncheckedIOException.
Java 8, together with the Stream API.
Yes. It keeps only the current line in memory, as long as you do not collect every line into a list.

Next: Files.list()

Get a lazy Stream of the entries directly inside a folder (Java 8+).

list() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful