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?
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With