Home Java Files Methods lines() Java Files lines() Method 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:
try (Stream<String> lines = Files.lines(log)) {
long errors = lines.filter(l -> l.contains("ERROR")).count();
} Call What 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 public static Stream<String> lines(Path path) throws IOException
public static Stream<String> lines(Path path, Charset cs) throws IOException Parameters Parameter Description pathThe text file to read. cs(Second overload) Charset for decoding.
Return Value Return Value Description Stream<String>A lazily populated stream of lines; closing it closes the file.
Important
Opening a missing file throws NoSuchFileException right away. Errors that happen while the stream is being consumed, such as invalid UTF-8, arrive as UncheckedIOException, because stream operations cannot throw checked exceptions. Forgetting to close the stream leaks a file handle.
Compare with Similar Methods Line-reading options:
Java Examples 1. Count matching lines 2. Stop early 3. Errors during reading Example 1 — Count ERROR Lines in a Log Stream the lines, keep those containing ERROR, and count them.
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);
}
} Run with java LinesCountErrors. The output is the same on Windows, macOS, and Linux.
ERROR lines: 2 How It Works Five log lines. Two of them begin with ERROR.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.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.
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);
}
} Run with java LinesFirstTwo. The output is the same on Windows, macOS, and Linux.
Preview: [Chapter 1, It was a dark night.]
Preview size: 2 How It Works A short-circuiting step. limit(2) asks for just two elements, and the stream stops pulling lines after that.Collect what you need. The two lines are copied into a list before the try block closes the stream.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.
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 One bad byte. 0xFF never appears in valid UTF-8, so decoding the file must fail.The stream opens fine. Files.lines itself succeeds; the problem is only found when count() starts reading.Wrapped exception. The checked MalformedInputException is wrapped in an UncheckedIOException; getCause() reveals the original.Frequently Asked Questions Do I need to close the stream from Files.lines? Yes. It keeps the file open until closed. Use try (Stream<String> s = Files.lines(path)) { ... }.
What is the difference between Files.lines and Files.readAllLines? lines returns a lazy Stream that reads as needed and must be closed; readAllLines reads everything into a List at once.
Why does Files.lines throw UncheckedIOException? Reading happens inside stream operations, which cannot throw checked exceptions, so I/O errors during reading are wrapped in UncheckedIOException.
Which Java version added Files.lines? Java 8, together with the Stream API.
Can Files.lines read huge files? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion