Site icon

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

1. Read file using java 8 lambda stream

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
Exit mobile version