Reading File lines easily with Java8 streams

Views: 74   

This post shows you how easily we can read file lines into Java8 streams. Following is the program to do that in Java 8

File content ( Path /experimental/sample.txt )

foo
bar

Program to read lines


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

public class ReadFileLines {
    public static void main(String args[]) {
        String filePath = "/experimental/sample.txt";
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("Error while reading the file!");
            e.printStackTrace();
        }
    }
}
On By