Mixing BufferedReader with DataInputStream

C

Chris Berg

I am reading data from an InputStream (from a Socket, but that is not
important). The data that arrives is mixed: Some of it is \n-separated
text lines, some is binary data. At a certain point I must switch from
reading lines to reading bytes. This could be done like this:

----- code begin -----
InputStream is= <get the stream from somewhere>
BufferedReader br=new BufferedReader(new InputStreamReader(is));

// first, read text:
while (true){
String st=br.readLine();
process(st);
if (nomorelines) break;
}

// now it's binary, read from the inputstream:
byte[] buf=new byte[1234]; // I know the length at this point
in.read(buf];
------ code end -------

However, this won't work, because BufferedReader reads ahead in an
internal data buffer. So, when the text-reading is finished, some of
the binary data has already been read and sits in the buffer.

One solution is to use a DataInputStream instead of the
BufferedReader, but that is deprecated, because it cannot handle
character conversion (as Sun says).

Another solution could be to read one byte at a time:

while (true){
int c=br.read();
if (c<0) break;
buf[i++]=c;
}

but that appears to be rather inefficient.

Any smarter solutions?

Chris
 
E

Esmond Pitt

Get rid of the BufferedReader and use a Reader that doesn't do buffering.
I ftyou must have buffereing, do it with a BufferedInputStream at a level
below both the Reader and the InputStream you are calling methods on.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top