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

孤者浪人 提交于 2019-12-25 05:19:18

问题


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.".

How does InputStream read() in Java determine that number of bytes?


回答1:


The buffer array has a defined length, call it n. The read() method will read between 1 and n bytes. It will block until at least one byte is available, unless EOF is detected.




回答2:


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.

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:

  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. However, subsequent calls to read() might not need to read the underlying source again until the in memory buffer is exhausted.
  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.

  3. Layers of Inputstreams wrapping other inputstreams such asnew GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); will use #1 and #2 above depending on the layer.



来源:https://stackoverflow.com/questions/25087665/how-does-inputstream-read-in-java-determine-the-number-of-bytes-to-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!