• Post Reply Bookmark Topic Watch Topic
  • New Topic

Re-Reading from the stream...

 
Nev Mehta
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Streams are behaving funny!!! i'll try to give you a gist of the problem instead of just blindly copy pasting the code...

I have,
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream in_raw = new DataInputStream(socket.getInputStream());

Somewhere in the code, in a while ( true ) loop i do this:-
while ( true ) {
String line = in.readLine();
if ( line.equals("aabbcc") )
break;
}

again; below i have another while ( true ) loop:-
while ( true ) {
for ( .. ; .. ; .. ) {
curr_byte = (byte)in_raw.read();
if ( curr_byte == -1 )
break;
}
}

Now, say i were to send the string 'aabbcc' from the other end using PrintWriter out = new PrintWriter(client.getOutputStream(), true); , in.readLine() does catch it but the problem is, so does (byte)in_raw.read(), so i end up reading byte values for the chars aabbcc again, which i dont want to. I guess when you read from a stream you automatically 'delete' contents of the stream however to make sure thats happening, i tried re initializing the in_raw, tried closing the in object but all in vain...

Does anyone know whats happening here?? Any fix for what I'm trying to do??

Thanks
Neville
 
Paul Clapham
Sheriff
Posts: 21889
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you use a BufferedReader, it reads a large block of bytes in advance, then gives those bytes out to you as you ask for them. (That's what "buffered" means.) Therefore the bytes that it's holding in its buffer are not available to your DataInputStream. Unexpected results, um, result.

So the short answer is, it's a bad idea to do that. Just have one stream that does all your reading. If you've got a protocol which makes that inconvenient, perhaps because you're mixing bytes with text, then that suggests the protocol should be revised too.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!