Java Stream How to - Convert File into a Stream








Question

We would like to know how to convert File into a Stream.

Answer

//from  w ww.  j  a  v  a2s .  co  m
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedReader reader = Files.newBufferedReader(Paths.get("a.bat"), StandardCharsets.UTF_8);
    //BufferedReader's lines methods returns a stream of all lines
    reader.lines().forEach(System.out::println);
  }
}

The code above generates the following result.