How to read from files with Files.lines(...).forEach(...)?

user3570058 picture user3570058 · Apr 24, 2014 · Viewed 61.1k times · Source

I'm currently trying to read lines from a text only file that I have. I found on another stackoverflow(Reading a plain text file in Java) that you can use Files.lines(..).forEach(..) However I can't actually figure out how to use the for each function to read line by line text, Anyone know where to look for that or how to do so?

Answer

pardeep131085 picture pardeep131085 · Apr 25, 2014

Sample content of test.txt

Hello
Stack
Over
Flow
com

Code to read from this text file using lines() and forEach() methods.

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 FileLambda {

    public static void main(String JavaLatte[]) {
        Path path = Paths.get("/root/test.txt");
        try (Stream<String> lines = Files.lines(path)) {
            lines.forEach(s -> System.out.println(s));
        } catch (IOException ex) {
          // do something or re-throw...
        }
    }
}