• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does read( ) method from InputStream return an int rather than a byte?  RSS feed

 
Edwardd Lee
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did some googling on this question and found an explanation that this is because read( ) can return -1 when the end of a file is reached, and since -1 is a valid byte, there's no way to distinguish if -1 is from the stream or is an indicator that the end is reached. However, isn't -1 also a valid int? What am I missing here? Thanks in advance!
 
Stephan van Hulst
Saloon Keeper
Posts: 7984
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is the bitwise representation.

-1 in int precision is 11111111 11111111 11111111 11111111, while in byte precision it's 11111111.

With byte precision, there's no way to signal an end of the stream. With an int, 11111111 11111111 11111111 11111111 is used to signal the end, while 00000000 00000000 00000000 11111111 is used to send the value -1 (which looks like the value 256 in int precision, but you get -1 after casting the int to a byte).

If you expect your files to be a certain length, you can use exceptions instead:
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is in the Java docs for Inputstream#read().  I can usually get to the Java docs quickly by Googling "java 8 <search>", changing <search> to whatever you are looking for.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!