Class LimitedInputStream
java.lang.Object
java.io.InputStream
org.refcodes.io.LimitedInputStream
- All Implemented Interfaces:
Closeable, AutoCloseable
A
LimitedInputStream wraps an InputStream and exposes at most
a fixed number of bytes from it.
Once the configured limit is reached, all read operations behave as if end of
stream was reached (returning -1).
This is useful when parsing framed or section based binary formats where a
component must not read beyond its assigned payload region.-
Constructor Summary
ConstructorsConstructorDescriptionLimitedInputStream(InputStream aInputStream, long aLimit) Creates aLimitedInputStreamthat allows reading at mostaLimitbytes from the provided stream.LimitedInputStream(InputStream aInputStream, long aLimit, boolean isDelegateClose) Creates aLimitedInputStreamthat allows reading at mostaLimitbytes from the provided stream. -
Method Summary
Methods inherited from class InputStream
nullInputStream, read, readAllBytes, readNBytes, readNBytes, skipNBytes, transferTo
-
Constructor Details
-
LimitedInputStream
Creates aLimitedInputStreamthat allows reading at mostaLimitbytes from the provided stream. The wrapped stream is not closed by this wrapper.- Parameters:
aInputStream- The underlying stream to read fromaLimit- The maximum number of bytes that can be read, must be >= 0- Throws:
NullPointerException- ifaInputStreamis nullIllegalArgumentException- ifaLimitis negative
-
LimitedInputStream
Creates aLimitedInputStreamthat allows reading at mostaLimitbytes from the provided stream. The wrapped stream is not closed by this wrapper depending on the according constructor'sdelegate closeflag.- Parameters:
aInputStream- The underlying stream to read fromaLimit- The maximum number of bytes that can be read, must be >= 0isDelegateClose- Iftrue, thenclose()closes the wrapped stream. Iffalse, thenclose()is a no-op.- Throws:
NullPointerException- ifaInputStreamis nullIllegalArgumentException- ifaLimitis negative
-
-
Method Details
-
remaining
public long remaining()Returns how many bytes are still available within the limit. -
read
- Specified by:
readin classInputStream- Throws:
IOException
-
read
- Overrides:
readin classInputStream- Throws:
IOException
-
skip
- Overrides:
skipin classInputStream- Throws:
IOException
-
available
- Overrides:
availablein classInputStream- Throws:
IOException
-
mark
public void mark(int readlimit) - Overrides:
markin classInputStream
-
reset
- Overrides:
resetin classInputStream- Throws:
IOException
-
markSupported
public boolean markSupported()- Overrides:
markSupportedin classInputStream
-
close
Closes this stream. If this instance was created withisDelegateClose == true, then the underlying stream is closed as well. Otherwise this method is a no-op, which is convenient when reading a limited payload from a larger container stream.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Overrides:
closein classInputStream- Throws:
IOException
-