Class GuardedInputStream

  • All Implemented Interfaces:
    Closeable, AutoCloseable


    public class GuardedInputStream
    extends MeasuredInputStream
    This filtered stream places an initial limit on the number of bytes that can be read. Once this limit is reached, all methods in this object return -1 indicating we're at the EOF, although the underlying InputStream is not touched.

    This object is useful when parsing files where specific blocks of a file have a predetermined size: with this object you can guarantee you read only a fixed number of bytes. So if data inside the block is corrupt, or if you want to loosely guard how you read each block, this object will make sure you don't read too far.

    The mark() and reset() methods are not supported.

    • Constructor Detail

      • GuardedInputStream

        public GuardedInputStream(InputStream in,
                                  long limit,
                                  boolean canClose)
        Constructs a new GuardedInputStream.
        Parameters:
        in - the underlying InputStream to use.
        limit - the maximum number of bytes that will be read.
        canClose - if this is false, then calling close will not actually close the underlying stream.
    • Method Detail

      • isAtLimit

        public boolean isAtLimit()
        Whether any more data can be read from this stream (due to the limit it was constructed with).
        Returns:
        true if the limit has been reached, and no more data can be read.
      • mark

        public void mark(int readlimit)
      • markSupported

        public boolean markSupported()
      • getRemainingLimit

        public long getRemainingLimit()
        Returns the number of bytes that are allowed to be read.

        This number has nothing to do with the number of bytes that are actually remaining in the underlying InputStream. For example, if this GuardedInputStream was designed to read at most 1000 bytes, then this method may return 1000 -- even though there may only be 500 bytes available in the underlying InputStream.

        Returns:
        the number of bytes that are allowed to be read.