简体   繁体   English

Java中的InputStream read()如何确定要读取的字节数?

[英]How does InputStream read() in Java determine the number of bytes to read?

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read() http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

The doc says "Reads some number of bytes from the input stream and stores them into the buffer array b.". 该文档说:“从输入流中读取一定数量的字节,并将其存储到缓冲区数组b中。”

How does InputStream read() in Java determine that number of bytes? Java中的InputStream read()如何确定该字节数?

The buffer array has a defined length, call it n . 缓冲区数组具有定义的长度,将其称为n The read() method will read between 1 and n bytes. read()方法将读取1到n个字节。 It will block until at least one byte is available, unless EOF is detected. 除非检测到EOF,否则它将阻塞直到至少一个字节可用。

I think the confusion comes from what "read" means. 我认为混淆来自“阅读”的含义。

read() returns to you the next byte in the InputStream or -1 if there are no more bytes left. read()将向您返回InputStream中的下一个字节,如果没有其他字节,则返回-1。

However, due to implementation details of the particular InputStream you are using, the source that contains the bytes being read might have more than one byte read in order to tell you the next byte: 但是,由于要使用的特定InputStream的实现细节,包含要读取的字节的源可能要读取一个以上的字节才能告诉您下一个字节:

  1. If your InputStream is buffered, then the entire buffer length might be read into memory just to tell you what the next byte is. 如果对InputStream进行了缓冲,则可能会将整个缓冲区长度读入内存,只是告诉您下一个字节是什么。 However, subsequent calls to read() might not need to read the underlying source again until the in memory buffer is exhausted. 但是,后续的对read()的调用可能不需要再次读取基础源,直到内存缓冲区中的内容耗尽为止。
  2. If your InputStream is reading a zipped file, then the underlying source may have to have several bytes read in to unzip your data in order to return the next unzipped byte. 如果您的InputStream正在读取压缩文件,则底层源可能必须读入几个字节才能解压缩数据,以便返回下一个解压缩字节。

  3. Layers of Inputstreams wrapping other inputstreams such as new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); 输入流的各层包装其他输入流,例如new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); will use #1 and #2 above depending on the layer. 根据层的不同,将使用上面的#1和#2。

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

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