How to Cache InputStream for Multiple Use

后端 未结 10 1021
庸人自扰
庸人自扰 2020-11-29 05:57

I have an InputStream of a file and i use apache poi components to read from it like this:

POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
         


        
10条回答
  •  独厮守ぢ
    2020-11-29 06:37

    Use below implementation for more custom use -

    public class ReusableBufferedInputStream extends BufferedInputStream
    {
    
        private int totalUse;
        private int used;
    
        public ReusableBufferedInputStream(InputStream in, Integer totalUse)
        {
            super(in);
            if (totalUse > 1)
            {
                super.mark(Integer.MAX_VALUE);
                this.totalUse = totalUse;
                this.used = 1;
            }
            else
            {
                this.totalUse = 1;
                this.used = 1;
            }
        }
    
        @Override
        public void close() throws IOException
        {
            if (used < totalUse)
            {
                super.reset();
                ++used;
            }
            else
            {
                super.close();
            }
        }
    }
    

提交回复
热议问题