I am using BufferedReader
to check for multiple strings if they exist within a file and i am using the below script:
int n = 41; // The line number
String line;
BufferedReader br = new BufferedReader(new FileReader(context.tfilelistdir));
for (int i = 0; i < n; i++)
{
line = br.readLine();
if (line.contains("$$WORDS$$ ABC") && line.contains("$$WORDS$$ XYZ"))
{
do something
}
}
Here I need to check if the string $$WORDS$$ ABC
and also $$WORDS$$ XYZ
both exist in different rows/cols within the csv file. BufferedReader's line does not accept &&
. It only works with ||
(OR) condition BufferedReader overwrites the entries as it keeps reading the records.
Any way to check if both condition exist (strings exist) within the CSV file?
If the substrings are in different lines, some boolean flags need to be introduced to track each specific condition.
Also, it's better to use try-with-resources
to ensure the file/reader resources are closed properly, and check if the file end is not reached in the reading process (then br.readLine()
returns null
).
int n = 41; // The line number
String line;
try (BufferedReader br = new BufferedReader(new FileReader(context.tfilelistdir))) {
boolean foundABC = false;
boolean foundXYZ = false;
int i = 0;
while ((line = br.readLine()) != null && i++ < n) { // read at most n lines
foundABC |= line.contains("$$WORDS$$ ABC"); // will be true as soon as ABC detected
foundXYZ |= line.contains("$$WORDS$$ XYZ"); // will be true as soon as XYZ detected
if (foundABC && foundXYZ) { // not necessarily in the same line
//do something
}
}
}