简体   繁体   English

在Java中读取输入流

[英]reading an input stream in java

I am reading an input stream in java. 我在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. 有没有办法让流保持打开,直到我在同一个流上进行进一步处理。

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. 您可能应该能够在开始时使用mark() ,然后调用reset()返回标记。 However, it depends on whether the stream supports that. 但是,它取决于流是否支持。

If you're using a file, you might want to consider using RandomAccessFile . 如果您使用的是文件,则可能要考虑使用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 ByteArrayInputStream s as you want backed by the same data. 如果它是来自网络的流,可能没有“倒带”它的概念 - 在这种情况下,您可能应该首先读取所有数据并将其复制到ByteArrayOutputStream :然后您可以将其转换为字节数组并创建为您想要由相同数据支持的许多ByteArrayInputStream

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). 另一种方法是读取整个数据并处理数据,以防您处理的数据不是太大(再次取决于您的应用程序特定需求)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM