Search code examples
javainputstream

Difference between the end of file and a byte value of -1 in Java?


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 ?


Solution

  • 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 range 0 to 255. 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.