简体   繁体   中英

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?

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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM