Search code examples
javainputstreamoutputstreamdatainputstream

Java: InputStreams and OutputStreams being shared


Can I share an InputStream or OutputStream?

For example, let's say I first have:

DataInputStream incoming = new DataInputStream(socket.getInputStream()));

...incoming being an object variable. Later on I temporarily do:

BufferedReader dataReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

I understand that the stream is concrete and reading from it will consume its input, no matter from where it's done... But after doing the above, can I still access both incoming and dataReader simultaneously or is the InputStream just connected to ONE object and therefore incoming loses its input once I declare dataReader? I understand that if I close the dataReader then I will close the socket as well and I will refrain from this but I'm wondering whether I need to "reclaim" the InputStream somehow to incoming after having "transferred" it to dataReader? Do I have to do:

incoming = new DataInputStream(socket.getInputStream());

again after this whole operation?


Solution

  • Ok, I solved this myself.. interesting links:

    http://www.coderanch.com/t/276168//java/InputStream-multiple-Readers

    Multiple readers for InputStream in Java

    Basically... the InputStream can be connected to multiple objects reading from it and consuming it. However, a BufferedReader reads ahead, so when involving one of those, it might be a good idea to implement some sort of signal when you're switching from for example a BufferedReader to a DataInputStream (that is you want to use the DataInputStream to process the InputStream all of a sudden instead of the BufferedReader). Therefore I stop sending data to the InputStream once I know that all data has been sent that is for the BufferedReader to handle. After this, I wait for the other part to process what it should with the BufferedReader. It then sends a signal to show that it's ready for new input. The sending part should be blocking until it receives the signal input and then it can start sending data again. If I don't use the BufferedReader after this point, it won't have a chance to buffer up all the input and "steal" it from the DataInputStream and everything works very well :) But be careful, one read operation from the BufferedReader and you will be back in the same situation... Good to know!