I am trying to write an utility which traverses through a list of files and searches for a string in each file. On finding the string in a file, I will add it to a list and display the list. Which design pattern should I use for the same?
Design patterns are named, recurring solutions to recurring problems that involve complex workflows, typically involving many classes with systematic relationships to each other. What you have here is a simple task that calls for a loop or two and a simple list data structure.
Ask again when you have to write a complex system with dozens of requirements that have complex interconnections with each other.
Kilian Foth's answer is excellent, so please upvote it, accept it, go by it.
This answer is simply meant to show the fallacy of trying to shoehorn patterns into everything.
First of all, you will need inversion of control. Your main application logic should not go out there on its own to access the filesystem and query files, it should be passed some interface that it can invoke to do the job. So, you should have a "SearchableEntity" interface and a class which implements it on java files, and you should have a "SearchableEntityProvider" interface to enumerate instances of "SearchableEntity" and a class which implements it for this particular application by "traversing through a list of files". So, your main application logic should be given a "SearchableEntityProvider" to work with.
Alternatively, you can use the visitor pattern, so the "SearchableEntityProvider" could invoke some "SearchableEntityConsumer" interface for each file, and your application could provide an implementation of "SearchableEntityConsumer" which performs each search, and if there is a match, adds the searchable entity to its list.
Then, of course, your main application logic should not be concerned with string-search specifics, so you should hide your strings behind some "SearchPattern" interface, and all the specifics of searching for a string behind some "SearchStrategy" interface.
You see where this is going: what could be done with 30 lines of code that fit in a single screen now takes 10,000 lines of code, a design document, and a quarter of your brain capacity to just maintain a grasp of the whole thing.
That having been said, let me add that if this is a homework assignment, where the teacher wants you to artificially force the use of a design pattern on an extremely simple problem which would not normally require the use of a design pattern, then the visitor pattern is probably what your teacher wants to see.