Java Streams  «Prev 

Cast int to byte in Java

If you want to store the raw bytes instead, you can cast the int to a byte.
byte[] b = new byte[10];
for (int i = 0; i < b.length; i++) {
  b[i] = (byte);
Of course, this produces a signed byte instead of the unsigned byte returned by the read() method (that is, a byte in the range -128 to 127 instead of 0 to 255).
However as long as you are clear in your mind and your code about which one you are working with, this doesn't present a problem.
Signed bytes can be converted back to ints in the range 0 to 255 like this:

int i = b >= 0 ? b : 256 + b;
When you call read(), you also have to catch the IOException that it might throw.
As I have observed, input and output are often subject to problems outside of your control:
  1. disks fail,
  2. hosting outage,
  3. network cables break.
Therefore, virtually any I/O method can throw an IOException, and read() is no exception. You do not get an IOException if read() encounters the end of the input stream; in this case, it returns -1.
You use this as a flag to watch for the end of stream.