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
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