Reading text files using the Stream API in Java 8
November 4, 2017 Leave a comment
We discussed the Java 8 Stream API thoroughly on this blog starting here. We mostly looked at how the API is applied to MapReduce operations to analyse data in a stream.
The same API can be applied to File I/O. Java 8 adds a new method called “lines” to the BufferedReader object which opens a Stream of String. From then on it’s just standard Stream API usage to filter the lines in the file – and perform other operations on them in parallel such as filtering out the lines that you don’t need.
Here’s an example how you can read all lines in a file: