在java中读取输入流
我正在读取 java 中的输入流。一旦输入流到达文件末尾,该流就会关闭,我无法再次使用相同的流。有什么方法可以保持流打开,直到我对同一流进行进一步处理。
I am reading an input stream in java. As soon as the end of file is reached in the input stream,the stream gets closed and I am unable to use the same stream again. Is there any way to keep the stream open until I do further processing on the same stream.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
流不应该仅仅因为您读到它的末尾而自动关闭。您应该能够在开始时使用
mark()
,然后调用reset()
返回标记。但是,这取决于流是否支持。如果您使用文件,则可能需要考虑使用
RandomAccessFile
。如果它是来自网络的流,则可能没有“倒回”它的概念 - 在这种情况下,您可能应该首先读取所有数据并将其复制到 ByteArrayOutputStream 中:然后您可以将其转换转换为字节数组,并根据需要创建由相同数据支持的任意数量的 ByteArrayInputStream。The stream shouldn't be automatically closed just because you read to the end of it. You should potentially be able to use
mark()
at the start and then callreset()
to get back to the mark. However, it depends on whether the stream supports that.If you're using a file, you might want to consider using
RandomAccessFile
. If it's a stream from the network, there may be no concept of "rewinding" it - in which case you should probably first read all of the data and copy it into aByteArrayOutputStream
: then you can convert that into a byte array and create as manyByteArrayInputStream
s as you want backed by the same data.当遇到流末尾时,流不会自动关闭。顺便说一句,我不确定如果无论如何都到达流末尾,为什么要保持流打开。如果您计划从流中读取两次(由于某种奇怪的原因在同一流上进行两次迭代),您可以关闭第一个流并打开第二个(如果可能的话)(对于文件流来说足够简单)。另一种方法是读取整个数据并处理该数据,以防您正在处理的数据不太大(同样取决于您的应用程序的特定需求)。
The stream is not automatically closed when the end of stream is encountered. BTW, I'm not sure why you want to keep the stream open if the end of stream is reached anyways. If you are planning on reading from the stream twice (two iterations over the same stream for some weird reason), you can close the first one and open a second one if that's possible (easy enough for file streams). Another method would be to read in the entire data and process that data in case the data you are dealing with isn't too large (again depends on your application specific needs).