Class FixedLengthInputStream

java.lang.Object
java.io.InputStream
com.ns.tcpframework.FixedLengthInputStream
All Implemented Interfaces:
Closeable, AutoCloseable

public class FixedLengthInputStream extends InputStream
A specialized InputStream that reads a fixed number of bytes from an underlying InputStream.

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 Details

    • FixedLengthInputStream

      public FixedLengthInputStream(InputStream in, long length)
      Constructs a FixedLengthInputStream with the specified underlying InputStream and length.

      The constructed stream will allow reading at most length bytes from the underlying stream. Subsequent read attempts after consuming length bytes 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 - if in is null.
  • Method Details

    • read

      public int read() throws IOException
      Reads the next byte of data from the stream.

      If the specified number of bytes has been read (i.e., remaining reaches 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:
      read in class InputStream
      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.