Am I closing my input stream correctly in Java?

前端 未结 2 1476
感情败类
感情败类 2021-01-25 17:29

I created a class that extends InputStream so that I can keep count of the number of bytes being read and throw an exception if it exceeds a max limit that I define.

Her

2条回答
  •  不知归路
    2021-01-25 17:42

    If LimitedSizeInputStream extends InputStream and wraps another stream, then @areus's solution is the best one.

    An alternative approach would be to extend FilterInputStream, like this:

    public class LimitedSizeInputStream extends FilterInputStream
    {
        private final long maxSize;
        private long total;
    
        public LimitedSizeInputStream(InputStream original, long maxSize)
        {
            super(original);
            this.original = original;
            this.maxSize = maxSize;
        }
    
        // use 'this.in' instead of 'this.original'
        // at least one of the 'read' methods needs to be overridden.
    }
    

    Note that FilterInputStream provides default implementations of the API methods that may prove useful.

    The javadoc provides details of what the default method implementations do.

提交回复
热议问题