Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader not stating 'ready' when it should

I am trying to read text from a web document using a BufferedReader over an InputStreamReader on an URL (to the file on some Apache server).

String result = "";
URL url = new URL("http://someserver.domain/somefile");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(), "iso-8859-1"));

result += in.readLine();

Now this works just fine. But Obviously I'd like the reader not to just read one line, but as many as there are in the file.
Looking at the BufferedReader API the following code should do just that:

while (in.ready()) {
    result += in.readLine();
}

I.e. read all lines while there are more lines, stop when no more lines are there. This code does not work however - the reader just never reports ready() = true!

I can even print the ready() value right before reading a line (which reads the correct string from the file) but the reader will report 'false'.

Am I doing something wrong? Why does the BufferedReader return 'false' on ready when there is actually stuff to read?

like image 295
fgysin Avatar asked Jan 21 '11 14:01

fgysin


People also ask

What does BufferedReader ready do?

ready() method informs whether the stream is ready to be read. A buffered character stream is only ready when the buffer is not empty or if the underlying stream is ready.

What exceptions should be handled when using BufferedReader?

IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc.

Does BufferedReader need to be closed?

When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.


1 Answers

ready() != has more

ready() does not indicate that there is more data to be read. It only shows if a read will could block the thread. It is likely that it will return false before you read all data.

To find out if there is no more data check if readLine() returns null.

String line = in.readLine();
while(line != null){
   ...
   line = in.readLine();
}
like image 178
josefx Avatar answered Oct 30 '22 01:10

josefx