09 Sep 23
Java – Cloning an InputStream
There’s a moment when you have been given an InputStream, with its markSupported returned “False”. This means you could only read the stream one and only once, as you can’t call “reset” on it. So, what to do if you want to read the stream for more than one time and be able to re-read the previously read data. The answer is “CLONE”. My very own approach would be to use Apache Commons to turn the stream into string in which it acts as a base. Whenever i need that InputStream, i turns the string back into an stream without affecting the read position and data lost. OK, here’s the steps.
Suppose you got a request object with InputStream.
// request is the Request Object // Turns InputStream into string String base = IOUtils.toString(request.getInputStream()); // Whenever you need the InputStream // Turn the string back to InputStream this way InputStream in = new ByteArrayInputStream(base.getBytes());