简体   繁体   中英

InputStreamReader.read() how does it 'not' read already read buffers?

I was using the code below and was just wondering why whenever the while loop is repeated, inputBuffer reads from the end of what had been last read.

What's stopping it from reading the same 500 characters all the time as the loop goes around? Is it just how InputStreamReader is constructed?

So what I got from Java site is below.

Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

It does say it reads until the end is reached but what's stopping it from assuming that the end has already been reached because the character buffer size is smaller than the whole InputStream when it goes around the first while loop?

I have a little bit more code related to this but I think you guys can sufficiently understand how it goes.

StringBuilder tempBuffer = new StringBuilder();

InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int charRead;
char[] inputBuffer = new char[500];

while (true){
    charRead = isr.read(inputBuffer);
    if (charRead <=0){
    break;
    }
    tempBuffer.append(String.copyValueOf(inputBuffer, 0, charRead));
}

return tempBuffer.toString();

InputStreamReader is just a wrapper around an InputStream .

Any InputStream is just a wrapper around some file or socket or other resource provided by the operating system.

The operating system knows where you've read to and delivers data to the next read operation starting from that position, and increments the position accordingly. Or, in the case of a socket for example, it has already thrown away the data you've already read.

It doesn't have anything to do with the Reader or the InputStream .

An obvious exception to this is ByteArrayInputStream , which provides its own position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM