How to convert File into a Stream in Java?


Let’s say we have a file “input.txt” here in the directory E:/ with the following content:

Open a file with Bufferedreader. We have taken the above file here which is located at E: directory;

BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\input.txt"),StandardCharsets.UTF_8);

Now get the stream of lines from the above file and display:

buffReader.lines().forEach(System.out::println);

The following is an example to convert File into a Stream in Java:

Example

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\input.txt"), StandardCharsets.UTF_8);
      System.out.println("Stream of lines...");
      buffReader.lines().forEach(System.out::println);
   }
}

Output

Stream of lines...
Amit
Tom
David
Andre
Keemo
Gayle

Updated on: 30-Jul-2019

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements