In this Java tutorial, you will learn how to read contents of a File line by line using Stream in Java, with examples.

Read file line by line using Stream in Java 8

The steps to read contents of a File line by line using Stream in Java are

Step 1: Use Files.lines to get Stream[https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html]<String>

Stream<String> stream = Files.lines(Path path, Charset cs)

Stream<T> contains elements of type T. Stream<String> contains strings which are lines from the contents of  file(specified by the Path).

Step 2: Use Stream.forEach(action)[https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-] to do the specified action on each String of the Stream<String> object.

stream.forEach(System.out::println);

We chose the action to “Print the String element (here line) to the output console”.

Examples

ADVERTISEMENT

1. Read File Line by Line – Java 8 Stream

In this example, we have a text file named samplefile.txt, and we will read contents of this file, line by line, using Stream class.

samplefile.txt

This is first line.
This is second line.
This is third line.
Welcome to www.tutorialkart.com.

Example.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
 
/**
* Read contents of a File line by line using Stream in Java 8
* www.tutorialkart.com
*/
public class Example {
    public static void main(String[] args) {
        String filename = "samplefile.txt";
        Path path = Paths.get(filename);
        Stream<String> stream;
        try {
            // read the contents of the file to a Stream
            stream = Files.lines(path);
            // System.out::println is the action to be done on each element, i.e., line in the file
            stream.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("There is an exception because of the file. Please check.");
            e.printStackTrace();
        }
    }
}

When the above program is run, output to the console is as shown in the following.

Output

This is first line.
This is second line.
This is third line.
Welcome to www.tutorialkart.com.

Note: Provide the path to the file correctly. In this example, the file is placed at the root of Project Folder (of Eclipse Project).

Conclusion

In this tutorial we have seen how to use java.util.stream.Stream to read the contents of a file line by line.