简体   繁体   English

bufferedReader.readLine()永远不会等于null

[英]bufferedReader.readLine() will never equal null

I am writing some code that will pull a name and id from a text file. 我正在编写一些代码,该代码将从文本文件中提取名称和ID。 To do this I am using a while loop. 为此,我使用了while循环。 It appears that the while loop condition is always true and the program never breaks out of the while loop. 看起来while循环条件始终为true,并且程序永远不会脱离while循环。 The code is shown below Any help will be appreciated. 该代码如下所示。任何帮助将不胜感激。 Thanks. 谢谢。

while((line = br.readLine()) != null) {
            line = br.readLine();
            endOfFirstName = line.indexOf(",");
            first_name = line.substring(0, endOfFirstName);
            endOfLastName = line.indexOf(" ");
            last_name = line.substring(endOfFirstName + 1, endOfLastName);
            id = line.substring(endOfLastName + 1);
        }

This condition 这种情况

while((line = br.readLine()) != null)

Is used to handle a stream ending / being closed - 用于处理流结束/被关闭的流-

From the docs : 从文档

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached. 一个字符串,其中包含行的内容,不包含任何行终止符;如果已到达流的末尾,则为null。

You must handle your own loop termination - depending on what you deem to be loop close worthy. 您必须处理自己的循环终止-取决于您认为值得循环关闭的条件。

ie In a standard HTTP request, this is done by a blank newline. 即在标准HTTP请求中,这是通过空白换行符完成的。

edit 编辑

You are also discarding every other line from your stream 您还将丢弃流中的所有其他行

Remove the extra 删除多余的

line = br.readLine();

As this is already handled by the loop. 因为这已经由循环处理了。

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

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