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?
The
BufferedReader.ready()
method is behaving as specified:The
Reader.ready()
javadoc says the following:Then the
BufferedReader.ready()
javadoc says the following:If you put these two together, it is clear that
BufferedReader.ready()
can returnfalse
in situations where are characters available. In short, you shouldn't rely onready()
to test for logical end-of-file or end-of-stream.I think the standard way to write this is to just attempt to read the line and verify that it returned sometime. Something like this:
So you just continue to go until you get null returned from the stream. See here for extra information:
http://download.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()
Basically the BufferedReader.ready() method can be used for checking whether the underlying stream is ready for providing data to the method caller.... else we can wait the thread for some time till it becomes ready.
But the real problem is that after we completely read the data stream, it will throw false.. so we didn't know whether the stream is fully read OR underlying stream is busy....
ready() != has more
ready()
does not indicate that there is more data to be read. It only shows if a readwillcould 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()
returnsnull
.Another way you can do this that bypasses the
in.ready()
is something like:You will just continue reading until you are done. This way you do not need to worry about the problem with
in.ready()
.If you want to use in.ready(), the following worked for me well: