Re: Mixing text and binary I/O
Ivan Voras wrote:
In implementing a network protocol, there's a text (ASCII) phase and a
binary phase. The ideal thing to use would be BufferedReader, but it
doesn't allow reading raw bytes. The next best thing (though slower)
would be DataInputStream, but its readLine() method is deprecated for
silly reasons (IMO). Any other suggestions?
In general there is no good way to do this using an InputStreamReader
wrapping the raw InputStream. The only way would require your protocol
to contain information that tells you how many of the following bytes
are part of the ASCII phase. You then read out those bytes, wrap it in a
ByteArrayInputStream and InputStreamReader. You cannot just read from
the InputStreamReader and then go back to InputStream. The problem is
that the character decoder can buffer up a few bytes and read ahead into
the InputStream.
You have to look beyond the original I/O classes and look into the new
I/O (NIO) classes that were introduced in JDK1.4. They will be able to
handle this better because the buffering can be more explicit. You can
use a ByteBuffer from which a CharsetDecoder extracts bytes. But it will
not have the problem of reading too far, becuase it can look into the
ByteBuffer without gobbling up the bytes.
See the NIO documentation.
--
Dale King