InputStream的skip操作是否影响mark-readlimit与reset的有效性?
Great question! Let's break this down clearly based on Java's InputStream specification and real-world implementation behavior:
Core Rule
Yes, the skip() operation does count against the readlimit set by mark(). That means the total number of bytes you read plus the number of bytes you skip after calling mark() must stay under the readlimit if you want reset() to successfully jump back to the marked position (assuming the stream supports mark/reset in the first place).
Why This Is The Case
Looking at the official API docs for InputStream.mark(int readlimit):
The
readlimitargument tells this input stream to allow that many bytes to be read before the mark position gets invalidated.
The key here is that "allow that many bytes to be read" is interpreted broadly to include any operation that advances the stream's position. Since skip(n) moves the stream pointer forward by n bytes (just like reading n bytes would), it consumes the same "budget" allocated by readlimit.
Example to Illustrate
Let's say you have a stream that supports mark/reset:
- You call
mark(10)to set a mark with a read limit of 10 bytes. - You read 3 bytes with
read()(total consumed: 3). - You skip 5 bytes with
skip(5)(total consumed: 3 + 5 = 8, which is under 10). - Calling
reset()here will successfully jump back to the marked position, because the total bytes moved (read + skipped) hasn't exceeded thereadlimit.
If instead you skipped 8 bytes after reading 3 (total 11, over 10), the mark position may be invalidated, and reset() could throw an IOException or fail to return to the correct position (depending on the stream implementation).
A Note on Implementations
While some stream implementations (like ByteArrayInputStream) might be more lenient and keep the mark even if you exceed the readlimit, you shouldn't rely on this. To ensure consistent behavior across all compliant InputStream implementations, always treat skip() bytes as part of the readlimit calculation.
内容的提问来源于stack exchange,提问作者Elist

