Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 612
user3570058 Avatar asked Apr 24 '14 17:04

user3570058


People also ask

What is the easiest way to read text files line by line in Java 8?

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed.

What does files Lines Path Path do?

What does Files. lines(Path path) do? Explanation: Files. lines(Path path) that reads all lines from a file as a Stream.


2 Answers

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 args[]) {
        Path path = Paths.of("/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...
        }
    }
    
}
like image 132
pardeep131085 Avatar answered Oct 08 '22 20:10

pardeep131085


Avoid returning a list with:

List<String> lines = Files.readAllLines(path); //WARN

Be aware that the entire file is read when Files::readAllLines is called, with the resulting String array storing all of the contents of the file in memory at once. Therefore, if the file is significantly large, you may encounter an OutOfMemoryError trying to load all of it into memory.

Use stream instead: Use Files.lines(Path) method that returns a Stream<String> object and does not suffer from this same issue. The contents of the file are read and processed lazily, which means that only a small portion of the file is stored in memory at any given time.

Files.lines(path).forEach(System.out::println);
like image 34
Imar Avatar answered Oct 08 '22 22:10

Imar