3

I'm trying to read java.io.InputStream multiple times starting from the top of the stream.

Obviously for streams that return true to markSupported() I can try and use mark(availableBytes) and then reset() to read stream again from the top.

Most of the streams do not support mark and those that do (e.g. java.io.BufferedInputStream) copy data into temporary byte array which is not nice in term of memory consumption, etc.

If my method receives java.io.InputStream as a parameter can I close it and then somehow reopen it to reset same original stream to the top so I can read it again?

I couldn't find any way to do this trick apart from writing original InputStream into memory (yak!) or temporary file and than opening new InputStream to those temporary locations if I need to read stream from top again.

parxier
  • 3,811
  • 5
  • 42
  • 54

1 Answers1

3

You can close it, but the only way to reopen the same stream to the same data without creating an explicit copy of the data somewhere is to determine what concrete type of InputStream you are dealing with (easy), what that stream was initialized to point at (may be easy, hard, or impossible depending upon the stream type and its interface), and then adding code to instantiate a new instance of the concrete stream type with the original source input (not difficult, but also not very maintainable and easily breakable if someone creates a custom InputStream implementation that you don't know how to handle).

aroth
  • 54,026
  • 20
  • 135
  • 176
  • You're right, it's not trivial with `InputStream`'s. I realized however that I was actually dealing with `ImageInputStream`'s that have reacher API for marking/reseting. – parxier Apr 13 '11 at 23:05