Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Files.lines read all lines into memory?

Tags:

java

file

In the doc it says

Read all lines from a file as a Stream.

Does that necessary mean that it's loading the entire file? For example:

try (Stream<String> stream = Files.lines(Paths.get("myfilename.txt"))) {
        stream.forEach(x -> {

if myfilename is 100GB , will Files.lines load the entire 100GB?

like image 724
Jal Avatar asked Mar 21 '18 01:03

Jal


People also ask

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.

How to read all lines in a file in Java 8?

Further more, Use method Files. readLines() method to get the all the lines in the form of java 8 Stream. Next, use forEach() method to get the each line of file and print into the console. * Java 8 example to read the file using Streams.

How do you read an efficient file in Java?

Reading Text Files in Java with BufferedReader If you want to read a file line by line, using BufferedReader is a good choice. BufferedReader is efficient in reading large files. The readline() method returns null when the end of the file is reached. Note: Don't forget to close the file when reading is finished.


Video Answer


2 Answers

Well, the link you provided states it already:

Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.

So for every time your for-each block is called, a new line is read.

like image 118
Izruo Avatar answered Oct 03 '22 08:10

Izruo


No, it doesn't load the entire file into memory. It internally uses a BufferedReader with the default buffer size, repeatedly calling readLine().

like image 33
shmosel Avatar answered Oct 03 '22 09:10

shmosel