Overview
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
- java.util.Optional
- java.util.stream.Stream
- java.nio.file.
- FileSystems
- Files
- Path
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 -> l.contains(searchTerm)) .findFirst(); if(line.isPresent()){ System.out.println(line.get()); }else 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.
Conclusion
This article demonstrates how to find the required string from a text file.
In Summary:
- 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.