Reputation: 1633
In below code, I feel while() condition may not be correct, because I am calling the readLine() method twice, means not verifying the firstLine string in my if() condition from reader.
what is the correct way to verify if buffered reader (br) has not reached end of line.
try {
if (is != null) {
br = new BufferedReader(new InputStreamReader(is));
os.write("x ample.abcd.com\r\n\r\n".getBytes());
if (br != null) {
while (br.readLine() != null) {
String returnString = br.readLine();
if (returnString.contains("250")) {
logger.debug(" string:" + returnString);
break;
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (sockt != null)
sockt.close();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Views: 1982
Reputation: 31699
You're right that your code is calling readLine()
twice. It calls it once when it evaluates the while
to see if the condition is true. Then, if it's true, the next statement calls it again, which means the previous line is lost.
If the code in EJP's answer looks too complex or not readable enough, here's another way:
while (true) {
String resultString = br.readLine();
if (resultString == null)
break;
// ... the rest of the loop
}
Upvotes: 1
Reputation: 311050
You are correct. It should be:
String line;
while ((line = br.readLine()) != null)
{
// ...
}
Upvotes: 1