Reading a stream in Java using BufferedReader using ready and readLine
Yesterday, I wrote a piece of code that reads a Java stream from a HTTP POST request. Here is the code.
while(bufferedreader.ready())
{
/*do some stuff here*/
}
The problem here is I am using the ready() method of the BufferedReader class. The ready() method returns true if the stream is ready. If it is false, then it will exit the while loop. The problem became obvious when I tried to transmit bigger data. The data that I am receiving becomes truncated at some point. The ready method somehow returns false in the middle of the transmission.
Now, to resolve this problem, I changed the ready to the example below.
while((strTmpLine = bufferedreader.readLine())!=null)
{
/*do some stuff here*/
}
This condition for this while loop tells us that this loop will continue while the result of readLine is not null. If it is null, then it will exit the loop. This is a better form of reading the buffered reader.