Search code examples
javainputstream

SocketInputStream and InputStream Supporting Reset() or MarkSupported()


I am trying to create a sample which is getting InputStream in the form of SocketInputStream. It is not supported reset() and mark(). Now once I process this input stream I can process it again for other operation because it get closed, reached at eof. Like I want to use this process for InputStream which is allowing reset() and markSupported().

How can I deal with InputStream in such situation.


Solution

  • Obviously, by default SocketInputStream does not support mark() and reset(). A network stream is not something that you can reposition. There is nothing that is storing the bytes that have been already read so the stream can never go back.

    That said, you could extend SocketInputStream and provide that functionality. You would need to override the SocketInputStream.read(byte b[], int off, int length) method and store information in a ByteArrayOutputStream or some other running byte[]. Whenever the mark is repositioned, you would need to read from the byte[] only issuing a super.read(...) if you are at the end of your internal array.

    It's a good bit of work to get right however and you are going to have to be very careful about memory here.