Search code examples
javabytefileinputstreamfileoutputstream

Java - read method in FileInputStream - Why the numbers are different in read() and in read(byte[] b)?


read() method returns an int that represents the next byte of data and read(byte[] b) method does not return anything, it assigns the bytes data values to the array passed as an argument.

I have made some tests with an image file and I have taken 2 ways:

  • Print the results returned by read() method until this result is -1 (what means that the end of the file has been reached).

  • Create an array of bytes and pass it as an argument of read(byte[] b) method and print the numbers that have been assigned to that array of bytes.

I have noticed that the results in both cases are different: in the second case, as the results are of byte type, the numbers were not greater than 127 or less than -128; while in the first case, i found numbers greater than 200, for example.

Should not the numbers be the same in both cases due to the fact that the file is the same in both cases and those numbers represent the data of that file?

I also used a FileOutputStream to write the data of the file into another new file and in both cases, the new file had the same bytes and look the same (as I said, it was an image).

Thank you.


Solution

  • Since Java has only signed datatypes, read(byte[] b) reads regular bytes, i.e. -128-127. However read() returns an int so it can indicate end of stream with -1, returning unsigned byte values from 0-255.

    byte b = (byte)in.read(); // Provided that stream has data left
    

    Would give you an unsigned byte looking like the values you've gotten in your byte[] b.