Reputation: 133
In java, bytes are signed (-128 to 127), this means an input stream may read a -1 without reaching the end of the file.
So how would a programmer know whether the -1 returned by an input stream indicates end of file or an actual byte value of -1 ?
Upvotes: 4
Views: 376
Reputation: 178263
When reading from an InputStream
, the read
method doesn't return a byte
; it returns an int
.
The value byte is returned as an
int
in the range0
to255
. If no byte is available because the end of the stream has been reached, the value-1
is returned.
Even though bytes are signed in Java, that doesn't matter here, because the byte that is read gets converted to an int
that can store values above 127. It also means that -1
for reaching the end of the stream won't get confused with a value of 255 that is read from the stream.
Once you have the value, you can always cast the int
to a byte
to get a byte in the range of -128 to 127, which would convert the 255 to -1.
Upvotes: 5