In this quick article, we’ll learn how to search a text file for any expected String pattern using Java 8 Streams. Although, there may be more than one way to achieve this, here in our example we have made use of Java 8 Streams and a couple of other libraries.
1. Involved Libraries
Let’s take a look at the code, followed by an explanation:
Here, first we define an Instance Path variable(path) that will hold our input file path.
Next, Inside the try block, we make use of a newly introduced method in Files class called Files.lines(<path>) which returns us all the lines of the input file as a Stream of String Objects. Later, we save the returned Strings into the instance variable streamOfLines of type Stream.
Finally, we call filter() on the streamOfLines, followed by a call to contain() method that checks for the expected(“streams“), further findFirst() is called which returns the expected Optional object.
This article demonstrates how to find the required string from a text file.
- We learned how to refer an external input file using java.nio.file libraries.
- How to effectively use Streams to filter the input file.
As usual, the code can be found on Github.