Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

file

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.

like image 758
mayur2j Avatar asked Dec 07 '25 17:12

mayur2j


1 Answers

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.

like image 135
Yash Soni Avatar answered Dec 09 '25 16:12

Yash Soni