How do I use BufferedReader.lines() method to read file?

The BufferedReader.lines() method is a Java 8 method that returns a Stream, each element of which is a line read from the BufferedReader. This allows you to perform operations on each line with Java’s functional programming methods.

Returning a Stream of strings makes the BufferedReader.lines() method very efficient in terms of memory usage when working with large files. It reads the file line by line, instead of loading the entire file into memory at once.

Here is how it’s used to read from a file:

package org.kodejava.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BufferedReaderLines {
    public static void main(String[] args) {
        Path path = Paths.get("README.MD");
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            reader.lines().forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code opens a BufferedReader on the file located at the given path and uses the lines() method to get a Stream of lines from the file. Each line is then printed to the console using the System.out::println method reference.

The try-with-resources statement is there to ensure that the BufferedReader is closed after we’re done with it, even if an exception was thrown. The catch block is to handle a potential IOException which would be due to a file read error.

Bear in mind that not every situation requires or benefits from using streams, and in some cases, traditional processing methods might be more suitable. But when dealing with large datasets and when you wish to write declarative, clean, and efficient code, this method can be extremely useful.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.