Prusprus Prusprus - 4 months ago 23
HTTP Question

Can't exit while loop in Java when extracting lines from BufferedReader

I'm trying to read lines from a BufferedReader in java by using a while loop. It will traverse through the BufferedReader as should, but when it should break from the loop it will 'freeze' the execution of the code. I've tried debugging the code but it the execution cue is lost after the loop. No idea what I'm doing wrong:

Code snippet:

BufferedReader reader = new BufferedReader(new InputStreamReader(yourSocket.getInputStream()));
String nextLine = null;

nextLine = reader.readLine();
while (nextLine != null){ //print all of input stream
nextLine = reader.readLine();

I've assumed that when there are no lines left in the BufferedReader that the nextLine variable would return null and break the loop. I've tried breaking the loop manually but it doesn't seem to work neither. Again, the code would print the BufferedReader's lines fine but any code following the while loop will not necessarily run.

If this info is not enough, please let me know. I can also past the full code if necessary.


seh seh

The problem appears to be that your Reader is wrapped around a blocking Socket, which will not indicate end-of-stream until the peer closes the connection (or your side closes the connection). You may have read all that's available, but when you try to read more, the underlying InputStream blocks trying to read more data from the socket.

When some data eventually becomes available, the InputStream will make that data available to the Reader, and, once the Reader has seen enough to constitute a complete line—or end-of-stream—you'll get your last line back out of the Reader. Trying to read the next line would finally return null.