简体   繁体   English

InputStreamReader.read()如何“不”读取已读取的缓冲区?

[英]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. 我使用下面的代码,只是想知道为什么每当重复while循环时,inputBuffer都会从上次读取的末尾读取。

What's stopping it from reading the same 500 characters all the time as the loop goes around? 是什么阻止它随着循环不断地读取相同的500个字符? Is it just how InputStreamReader is constructed? 只是InputStreamReader的构造方式吗?

So what I got from Java site is below. 因此,我从Java网站获得的内容如下。

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. 该方法将阻塞,直到某些输入可用,发生I / O错误或到达流的末尾为止。

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? 它确实说它一直读到到达末尾,但是如果因为它在第一个while循环周围时字符缓冲区的大小小于整个InputStream的大小,那么是什么阻止了它已经到达末尾呢?

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 . InputStreamReader只是周围的包装InputStream

Any InputStream is just a wrapper around some file or socket or other resource provided by the operating system. 任何InputStream都只是操作系统提供的某些文件或套接字或其他资源的包装。

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 . 它与ReaderInputStream无关。

An obvious exception to this is ByteArrayInputStream , which provides its own position. 一个明显的例外是ByteArrayInputStream ,它提供了自己的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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