1

I simply use

IOUtils.copy(myInputStream, myOutputStream);

And I see that before calling IOUtils.copy the input stream is avaible to read and after not.

flux.available()
     (int) 1368181 (before)
     (int) 0 (after)

I saw some explanation on this post, and I see I can copy the bytes from my InputStream to a ByteArrayInputStream and then use mark(0) and read(), in order to read multiple times an input stream.

Here is the code resulted (which is working). I find this code very verbose, and I'd like if there is a better solution to do that.

ByteArrayInputStream fluxResetable = new ByteArrayInputStream(IOUtils.toByteArray(myInputStream));
fluxResetable.mark(0);
IOUtils.copy(fluxResetable, myOutputStream);
fluxResetable.reset();
Community
  • 1
  • 1
Clemzd
  • 895
  • 2
  • 15
  • 35

1 Answers1

8

An InputStream, unless otherwise stated, is single shot: you consume it once and that's it.

If you want to read it many times, that isn't just a stream any more, it's a stream with a buffer. Your solution reflects that accurately, so it is acceptable. The one thing I would probably change is to store the byte array and always create a new ByteArrayInputStream from it when needed, rather than resetting the same one:

byte [] content = IOUtils.toByteArray(myInputStream);
IOUtils.copy(new ByteArrayInputStream(content), myOutputStream);
doSomethingElse(new ByteArrayInputStream(content));

The effect is more or less the same but it's slightly easier to see what you're trying to do.

biziclop
  • 48,926
  • 12
  • 77
  • 104