Search code examples
javainputstream

How does the InputStream read(byte []) method store data as bytes?


The byte code ranges from 0 to 256 (and -1 which indicates the EOF), but the java byte variable ranges from -128 to 128. How is that method able to store the bytes from the code into byte variables?


Solution

  • I'm not sure what you're unclear about:

    1. is.read(byte[]) reads an array of 8-bit values. The fact that those values are signed (-128..127, not "128")) is irrelevant.
    2. It doesn't need to store an out of band value like EOF. It simply stops reading at EOF. The array's .length is the buffer size and/or the #/bytes successfully read before EOF.
      PS: It's common practice to query the filesize and allocate the byte array before calling read().