繁体   English   中英

在缓冲读卡器中检查线路末端的适当条件

[英]proper condition to check end of line in buffered reader

在下面的代码中,我觉得while()条件可能不正确,因为我调用readLine()方法两次,意味着不从reader中验证if()条件中的firstLine字符串。

什么是验证缓冲读取器(br)是否未到达行尾的正确方法。

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();
    }

你是对的。 它应该是:

String line;
while ((line = br.readLine()) != null)
{
    // ...
}

您的代码正在调用readLine()两次是对的。 它在评估while时调用它一次以查看条件是否为真。 然后,如果是,则下一个语句再次调用它,这意味着前一行丢失。

如果EJP的答案中的代码看起来太复杂或不够可读,这是另一种方式:

while (true) {
    String resultString = br.readLine();
    if (resultString == null)
        break;
    // ... the rest of the loop
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM