Can I modify the bytes which are requested to read but not read in reality of InputStream?

62 Views Asked by At

In official JDK docs, the java.io.InputStream#read(byte[], int, int) said:

Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

But after the sentence, the next paragraph said:

In every case, elements b[0] through b[off-1] and elements b[off+len] through b[b.length-1] are unaffected.

The first sentence requires a more strong limitation of the read operation.

I'm writing an implementation that extends from the InputStream. The documentation said, "unaffected". I interpret it as it can't be modified during the read operation. But even for the b[off+k]~b[off+len-1] also is not able to be modified? I want to use the whole buffer [off, off+len) to processing data temporary.

2

There are 2 best solutions below

5
k314159 On BEST ANSWER

Concerning InputStream.read(byte[] b, int off, int len), the following scenarios are possible:

  1. There are len or more bytes available in the stream. In this case, the bytes b[off] to b[off + len - 1] will be written. All other bytes in the buffer b will not be modified.

  2. There are less than len bytes in the stream. Let k be the total number of bytes that can be read. In this case, the bytes b[off] to b[off + k - 1] will be written. All other bytes in the buffer b will not be modified.

In particular, your InputStream implementation is not allowed to first clear the contents of b from off to off + len - 1 before attempting to read the stream.

There are other possible scenarios: those involving exceptions. These scenarios are out of scope of this question.

1
Thomas Kläger On

The buffer b is conceptually split into for parts:

  • from 0 to off-1: these bytes are unaffected (2. paragraph)
  • from off to off+k-1: these contain the bytes that have been read (1. paragraph)
  • from off+k to off+len-1: this range was included in the read request but has not been changed because of insufficient data (1. paragraph)
  • from off+len to off+b.length-1: these bytes are unaffected (2. paragraph)

There is no overlap between those four ranges.