Sunday, May 23, 2021

ResetOnCloseStream or ReusableInputStream.

Read multiple times an input stream is a common requirement with built-in implementation as per my search. Obviously, this is very interesting to limit application java footprint memory by copying. 

Say that you need to process a file but also send a copy somewhere for audit purposes. I looked at solutions like common io with the implementation of pipes stream. Other suggestions involve a copy of the underlying stream. For these solutions, we need to store them somewhere which is not very practicable.

Then the solution is to cook something with a markable or mark supported stream via for instance a Buffered Input Stream. We need these methods from the API :

public synchronized void mark(int readLimit)
public synchronized void reset() throws IOException
public boolean markSupported()

The mark method marks the current position which the beginning of the reading process. We use max integer values or any big integer value so we can get back to the zero position safely.  This is not my idea, please read this discussion from StackOverflow: https://stackoverflow.com/questions/924990/how-to-cache-inputstream-for-multiple-use


I've kept the name which is very intuitive. I just add a method for closing the decorated stream and convert if needed the inputStream to decorate to a markable inputStream.

No comments:

Post a Comment