Stupid InputStreamReader/character question

R

Rick Genter

I have an InputStream on which I will be reading intermixed text and
binary data. When I go to read the text data, I create an
InputStreamReader from the InputStream and read characters one at a
time until I read a delimiter character. At that point, I go back to
reading raw bytes from the InputStream.

InputStreamReader.read() returns an int. I want to put these ints into
a String. Is the following what I should be doing?

StringBuffer buffer = new StringBuffer ();
InputStreamReader reader = new InputStreamReader (input);
int nextCharacter;

do
{
nextCharacter = reader.read ();
if (nextCharacter == -1) // shouldn't happen given protocol
throw new EOFException ();
if ((char) nextCharacter != DELIMITER)
buffer.append ((char) nextCharacter);
}
while ((char) nextCharacter != DELIMITER);

I hate having to cast nextCharacter, but I suppose that I have no
choice (yes, I can create a char variable and do the cast once, which
I probably will end up doing, but still...)

Thanks in advance.

Rick
 
C

Chris Berg

I have an InputStream on which I will be reading intermixed text and
binary data. When I go to read the text data, I create an
InputStreamReader from the InputStream and read characters one at a
time until I read a delimiter character. At that point, I go back to
reading raw bytes from the InputStream.

InputStreamReader.read() returns an int. I want to put these ints into
a String. Is the following what I should be doing?

StringBuffer buffer = new StringBuffer ();
InputStreamReader reader = new InputStreamReader (input);
int nextCharacter;

do
{
nextCharacter = reader.read ();
if (nextCharacter == -1) // shouldn't happen given protocol
throw new EOFException ();
if ((char) nextCharacter != DELIMITER)
buffer.append ((char) nextCharacter);
}
while ((char) nextCharacter != DELIMITER);

I hate having to cast nextCharacter, but I suppose that I have no
choice (yes, I can create a char variable and do the cast once, which
I probably will end up doing, but still...)

Thanks in advance.

Rick

I don't think it can be avoided. The real ugliness is, that the return
value of reader.read() has 2 uses: to return the character, and to
return the EOF status. Thus, 16 bits is not enough. Still, any
alternative I can think about would be slower executing. It seems that
Sun is turning away from using EOFExceptions, at they slow down normal
(non-EOF'ing) code on most VM's.

Chris
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top