Read a File Line By Line using Java 8 Stream API


To read a file line by line we can make use of the static lines(Path path) method from the Files class from the java.nio.file package.

Let's take a look at an example.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {

        String filePath = "/Users/dev/Documents/Java-Projects/demo/src/data.txt";

        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("Error occurred while reading the file!");
            e.printStackTrace();
        }
    }
}
Output - Read file line by line using Stream API

Note that lines() method was added to Files class in Java 8. It returns a Stream object using which we can iterate over the lines using the forEach() method.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap