简体   繁体   中英

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()

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?

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.

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 as new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))); will use #1 and #2 above depending on the layer.

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