How to convert File into a Stream in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 02-May-2019 07:55:27
Advertisements