Pratiyush Kumar Singh
Pratiyush Kumar Singh

Reputation: 1997

How to read file line by line in Java 8?

In Java 8 I see new method is added called lines() in Files class which can be used to read a file line by line in Java. Does it work for huge files? I mean can we load first 1000 lines then second set of 1000 lines. I have huge file with 1GB, Will it work?

Could someone share code snippet how to use it?

Upvotes: 8

Views: 2159

Answers (2)

MadConan
MadConan

Reputation: 3777

From the API (embolden by me)

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

This very strongly suggests that you can use this on any arbitrarily sized file, assuming your code doesn't hold all of the content in memory.

Upvotes: 0

Puce
Puce

Reputation: 38122

Does it work for huge files? [...] I have huge file with 1GB, Will it work?

As far as I can see it should work well for big files as well (but I haven't tried):

try(Stream<String> lines = Files.lines(path)){
    lines.filter(...).map(...)....foreach(...);
}

I mean can we load first 1000 lines then second set of 1000 lines.

How many lines are read at one time is implementation specific to Files.lines (which probably uses a BufferedReader, but I might be wrong).

Upvotes: 10

Related Questions