我可以关闭/重新打开InputStream来模拟不支持标记的输入流的标记/重置吗?
我试图从流的顶部开始多次读取 java.io.InputStream
。
显然,对于返回 true
到 markSupported()
的流,我可以尝试使用 mark(availableBytes)
然后使用 reset() 从顶部再次读取流。
大多数流不支持标记,而那些支持标记的流(例如java.io.BufferedInputStream)将数据复制到临时字节数组中,这在内存消耗等方面不太好。
如果我的方法接收到< code>java.io.InputStream 作为参数,我可以关闭它,然后以某种方式重新打开它以将相同的原始流重置到顶部,以便我可以再次读取它吗?
除了将原始 InputStream
写入内存(牦牛!)或临时文件,然后在这些临时位置打开新的 InputStream
之外,我找不到任何方法来做到这一点(如果我)需要再次从顶部读取流。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以关闭它,但在不创建数据的显式副本的情况下,重新打开同一数据流的唯一方法是确定您正在处理的具体类型的
InputStream
(简单),该流被初始化为指向什么(可能是简单、困难或不可能,具体取决于流类型及其接口),然后添加代码以使用原始源输入实例化具体流类型的新实例(并不困难,但如果有人创建了一个您不知道如何处理的自定义InputStream
实现,那么它也不太可维护且容易损坏)。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 customInputStream
implementation that you don't know how to handle).