Andrew Wang Andrew Wang - 1 year ago 80
Android Question

bufferedReader.readLine() will never equal null

I am writing some code that will pull a name and id from a text file. To do this I am using a while loop. It appears that the while loop condition is always true and the program never breaks out of the while loop. 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);

Answer Source

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.

You must handle your own loop termination - depending on what you deem to be loop close worthy.

i.e. In a standard HTTP request, this is done by a blank newline.


You are also discarding every other line from your stream

Remove the extra

line = br.readLine();

As this is already handled by the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download