Class FixedLengthInputStream
- All Implemented Interfaces:
Closeable, AutoCloseable
This class acts as a limiting wrapper around another InputStream, restricting the number of bytes that can be read to a predetermined length. Once the specified number of bytes has been read, the stream behaves as if it has reached the end-of-stream (EOF), even if the underlying stream has more data available.
This is particularly useful for:
- Reading HTTP request bodies with Content-Length headers
- Processing fixed-size chunks in streaming protocols
- Preventing over-reading from shared or multiplexed streams
- Enforcing size limits on incoming data
Thread-safety: This class is not thread-safe. External synchronization is required if an instance is accessed by multiple threads concurrently.
Example usage:
InputStream socket = clientSocket.getInputStream(); InputStream limitedStream = new FixedLengthInputStream(socket, 1024); // Can only read up to 1024 bytes, even if socket has more data
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionFixedLengthInputStream(InputStream in, long length) Constructs a FixedLengthInputStream with the specified underlying InputStream and length. -
Method Summary
Methods inherited from class InputStream
available, close, mark, markSupported, nullInputStream, read, read, readAllBytes, readNBytes, readNBytes, reset, skip, skipNBytes, transferTo
-
Constructor Details
-
FixedLengthInputStream
Constructs a FixedLengthInputStream with the specified underlying InputStream and length.The constructed stream will allow reading at most
lengthbytes from the underlying stream. Subsequent read attempts after consuminglengthbytes will return -1 (end-of-stream).- Parameters:
in- The underlying InputStream to read from. Must not be null.length- The maximum number of bytes to read from the underlying InputStream. Should be non-negative. A value of 0 creates a stream that is immediately at end-of-stream.- Throws:
NullPointerException- ifinis null.
-
-
Method Details
-
read
Reads the next byte of data from the stream.If the specified number of bytes has been read (i.e.,
remainingreaches 0), this method returns -1 to indicate the end of the stream, even if the underlying stream has more data available.This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
- Specified by:
readin classInputStream- Returns:
- The next byte of data as an integer in the range 0 to 255, or -1 if the end of the stream has been reached (either the fixed length limit was reached or the underlying stream ended).
- Throws:
IOException- If an I/O error occurs while reading from the underlying InputStream.
-