Optimal way to find if a string is present in a file

file, java, string

Solution

Since the file is containing a lot of lines, it will be better idea to read that file line-by-line, instead of getting all of it's content into program memory. So essentially, read one line check for presence of your string and move forward.

Problem

I have a text file containing thousands of lines. What would be the optimal way to find if a certain string exists in the file or not? Either by reading the whole file into a string & then using `string.contains` method or by creating a list of all the lines using `Files.readAllLines` method & then looping through each line from the list & check whether that line contains the required string or not? Update: I am using Java 7. The search is limited to 1-2 string searches per file(10 files).The string to be searched changes with the file. I want to stop the search if the string is found.

Original source

Related problems