Java 8 – Searching Text Files using Streams1 min read



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

2. Implementation

Let’s take a look at the code, followed by an explanation:

private static void searchStringFromFile() {
 Path path = FileSystems.getDefault()
  .getPath("files", "text_file.txt");
 String searchTerm = "streams";

 try(Stream <String> streamOfLines = Files.lines(path)) {
  Optional <String> line = streamOfLines.filter(l -> 
   System.out.println("Not found");
 }catch(Exception e) {}

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.
In Summary:

  1. We learned how to refer an external input file using java.nio.file libraries.
  2. How to effectively use Streams to filter the input file.

As usual, the code can be found on Github.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.