1. Read all lines of the file lazily
lines() method allows us to read file line by line lazily i.e. It returns Stream<String>.
2. lines() methods
Two versions of lines() method were introduced in Java 8. This methods bridge the file operations and Stream API. Stream API was added in Java 8 to write declarative and expressive code.
lines() method is used to read all the lines into the Stream lazily and then we can process that Stream in declarative way. Prior to lines() method we had method called readAllLines(). readAllLines() method is used to read all the lines into the List and return it.
Method | Return type | Lazy/Eager? |
lines() | Returns Stream<String> | Lazily populated |
readAllLines() | Returns List<String> | Eagerly populated |
There are two versions of lines() method. Let’s take a look at it.
3. lines(Path path, Charset cs)
Method signature
public static Stream<String> lines(Path path, Charset cs) throws IOException
lines(path, Charset) method reads all the lines as a Stream. Stream is populated lazily when the stream is consumed i.e. when a terminal operation on Stream is invoked.
Internally the lines() method creates a BufferedReader with the provided Path and Charset and calls method lines() which is provided in BufferedReader(provide link to BufferedReader class of blog) class.
This method can throw IOException if an I/O error occurs while opening a file.
Below is the example of using lines(Path, Charset) method where we try to find the longest word in words.txt file.
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.OptionalInt; import java.util.stream.Stream; Stream<String> stream = Files.lines( Paths.get("words.txt"), StandardCharsets.UTF_8); OptionalInt optMaxLength = stream.mapToInt(String::length).max(); Assert.assertEquals(OptionalInt.of(45), optMaxLength);
4. lines(Path path)
Method signature
public static Stream<String> lines(Path path) throws IOException
lines(Path) method is similar to lines(Path, Charset) method. This method also returns Stream which is lazily populated.
Internally lines(Path) method also creates a BufferedReader with the provided Path and uses StandardCharsets.UTF_8 as default Charset.
This method can throw IOException if an I/O error occurs while opening a file.
Below is the example of using lines(Path, Charset) method where we try to find the longest word in words.txt file.
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.OptionalInt; import java.util.stream.Stream; Stream<String> stream = Files.lines(Paths.get("words.txt")); OptionalInt optMaxLength = stream.mapToInt(String::length).max(); Assert.assertEquals(OptionalInt.of(45), optMaxLength);
5. Conclusion
lines() method serves the purpose to bridging the file operations and Stream APIs. Unlike the readAllLines() this method read the file lazily and opens an opportunity to perform Stream related operations.