• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does InputStreamReader not see the End of Stream from a ByteArrayInputStream on a read()?  RSS feed

 
Kenton Garner
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can someone explain why this code produces and infinite loop when executed.

The InputStreamReader does not appear to recognize the end of the byte [] that is being read via the ByteArrayInputStream.

This seems juvenile but I do not understand. (Note: in reality the byte[] may contain multiple byte UTF8 characters.)

 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reader.read() method returns -1 to report that it is past the end of the stream. But you convert that -1 to a char -- a data type whose values can only be between 0 and 65535. So the -1 will be converted to something in that range.

So then your code treats 0 as the end-of-stream signal. Presumably -1 isn't converted to 0 when its cast to a char -- my guess is that it's converted to 65535 -- and so your loop never ends.

So don't do the cast to char there. Do it inside the loop instead.
 
Kenton Garner
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
- thanks
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!