在java中读取输入流

发布于 2024-10-08 14:02:17 字数 83 浏览 0 评论 0原文

我正在读取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奈何桥上唱咆哮 2024-10-15 14:02:17

流不应该仅仅因为您读到它的末尾而自动关闭。您应该能够在开始时使用 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 call reset() 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 a ByteArrayOutputStream: then you can convert that into a byte array and create as many ByteArrayInputStreams as you want backed by the same data.

茶花眉 2024-10-15 14:02:17

当遇到流末尾时,流不会自动关闭。顺便说一句,我不确定如果无论如何都到达流末尾,为什么要保持流打开。如果您计划从流中读取两次(由于某种奇怪的原因在同一流上进行两次迭代),您可以关闭第一个流并打开第二个(如果可能的话)(对于文件流来说足够简单)。另一种方法是读取整个数据并处理该数据,以防您正在处理的数据不太大(同样取决于您的应用程序的特定需求)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文