How to Cache InputStream for Multiple Use

后端 未结 10 1055
庸人自扰
庸人自扰 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:22

    This is how I would implemented, to be safely used with any InputStream :

    • write your own InputStream wrapper where you create a temporary file to mirror the original stream content
    • dump everything read from the original input stream into this temporary file
    • when the stream was completely read you will have all the data mirrored in the temporary file
    • use InputStream.reset to switch(initialize) the internal stream to a FileInputStream(mirrored_content_file)
    • from now on you will loose the reference of the original stream(can be collected)
    • add a new method release() which will remove the temporary file and release any open stream.
    • you can even call release() from finalize to be sure the temporary file is release in case you forget to call release()(most of the time you should avoid using finalize, always call a method to release object resources). see Why would you ever implement finalize()?

提交回复
热议问题