There are quite a few issues with that code (most glaring: when you catch the 'FileNotFound' you should return and log a 'fatal' - no point in continuing).
I'm also assuming that your actual code is not the one you show (it wouldn't compile).
Anyways, here's how you read a file in Java:
public boolean isDuplicate(String lookup, String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
int lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
// best would be to use a regex to match against the line
// however, the naive approach would be
if (line.indexOf(lookup) != -1) {
log.info(String.format"Lookup term %s found on line %d", lookup, lineNo);
return true;
}
}
log.info(String.format("Lookup term %s not found in %s", lookup, filename);
return false;
} catch (IOException e) {
// log a fatal error and bail
log.error(String.format("Could not read from %s [%s]", filename, e.getLocalizedMessage()));
// here best practice would be to throw your own custom application ex
throw new MyApplicationException(e);
}
}
The while
and the for
both behave essentially the same way; the reason why your while
never "returned" is probably due to your "exhausting" the stream in the countlines()
method.