Read a file line by line using java 8 lambda stream (example)

1. Read file using java 8 lambda stream

  • Given a file, read input file by line by line using lambda stream in java 8.
  • Get the input file (“readFile.txt”) from class path or some absolute location.
  • We will use Java 7 feature try -with-resources, which will ensures that resources will be closed (automatically).
  • Read the input file, line by line.
  • Register onClose method to attach a task.
    • onClose method will be called, when read operation will be completed.
    • Printing the “Finished reading the file” when stream is closed.

2. Program – read input file line by line using java 8 stream lambda

package org.learn;

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

public class ReadFileLineByLine {

 public static void main(String[] args) throws IOException {
  /*
    Hello
   We are reading file
   using java 8
   Stream
   */
  Path file = Paths.get("readFile.txt");
  try(Stream<String>lines = Files.lines(file)
      .onClose(() -> System.out.println("Finished reading the file"))) {
   lines.forEach(System.out::println);
  }
 }
}

3. Output- read input file line by line (java 8 stream lambda)

Hello
We are reading file
using java 8
Files
Finished reading the file
Scroll to Top