简体   繁体   中英

reading an input stream in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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