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 receiv开发者_如何学编程es 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.
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).
精彩评论