I am reading from a BufferedReader, which is wrapping an InputStreamReader. The stream comes from a URL with myURL.openStream();
I am trying to read a portion of the stream (characters between startPos and endPos) into a String and then store it in a text file.
char[] buffer = new char[endPos-startPos];
reader.skip(startPos);
int i = 0;
while(i < (endPos-startPos)){
buffer[i] = (char) reader.read();
i++;
}
The above code works, but seems pretty slow.
I am trying to use the read(char[], int, int) method instead – I assume the Java people have implemented it quicker!
However – it gets about halfway through adding the desired characters into the string then finishes, leaving me with a half full char array.
According to Javadoc it only does this when it either reaches EOF, or “The ready method of the underlying stream returns false, indicating that further input requests would block”. Can anyone tell me what this means? And why is it happening if reading the characters one by one works fine? (Can’t be EOF!)
It’s slow because the data is arriving slowly. Nothing you can do about that in the receiving code.
read(char[] ...)returns prematurely because only that many bytes arrived after the first read blocked. If you want to read a specific number of characters you have to loop, either callingread()orread(char[], ...). AsBufferedReaderis, err, buffered, it won’t make any difference which one you call.