i was just wandering if this was a good or bad idea:
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(in);
DataInputStream dis = new DataInputStream(in);
Now I’d like to read from the BufferedReader. If a certain command (just a string) arrives, I’d like to continue reading from the DataInputStream.
Does this work? If yes, is it considered good or bad practice?
(I think your example is broken in terms of what is a reader and what is an input stream, but I get the question anyways)
You can do things like that, but you need to know exactly how each component is behaving with regards to buffering.
The socket input stream you are working from will only allow you to read a certain byte once (checkout
InputStream.markSupported()). You can wrap that input stream in aBufferedInputStreamthat effectively reads some bytes ahead but also adds the functionality to do amark()andreset().This means that any reader/input stream on top of the
BufferedInputStreamcan read ahead, mark, skip back etc. But here you need to be careful so that you don’t add another layer of “buffers” – i.e. aBufferedReader>InputStreamReader>BufferedInputStream>InputStream.So the answer is yes, it can be made to work, just know the exact behaviour of every component (I often see people throwing in
BufferedXXXjust for the hell of it).In your example I would do: