Am I closing my input stream correctly in Java?

前端 未结 2 1473
感情败类
感情败类 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.

    0 讨论(0)
  • 2021-01-25 17:43

    The try-with-resources only closes the declared resource. So will only close metadataStream.

    You should implement the close method in LimitedSizeInputStream to close the original stream.

    @Override
    public void close() throws IOException {
        original.close();
    }
    
    0 讨论(0)
提交回复
热议问题