Skip to content

Reading text files with Java 8 streaming API

Ramesh Fadatare edited this page Jul 11, 2019 · 1 revision

Another option to read text files is to use the Java 8 streaming API. The Files.lines() reads all lines from a file as a stream. The bytes from the file are decoded into characters using the StandardCharsets.UTF-8 charset.

Reading text files with Java 8 streaming API

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

public class ReadTextFileEx3 {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/resources/sample.txt";
        
        StringBuilder sb = new StringBuilder();
        
        Files.lines(Paths.get(fileName)).forEachOrdered(s -> {
            sb.append(s); 
            sb.append(System.lineSeparator());
        });
        
        System.out.println(sb);
    }
}

The contents of the sample.txt file are read and printed to the console using the Files.lines() method.

Clone this wiki locally