That's not the proper way to read a file, and the error is in the handling of
b. First of all, you check if it's -1 after you've written it to the output stream. Secondly, InputStream.read() returns an int value from -1 to 255 (inclusive). Everything but -1 indicates a valid byte. However, if you cast it to a byte, its range is changed to -128 to 127 (inclusive).
-1 is in there twice -- once as -1 cast to byte, and once as 255 cast to byte. That's why the method returns an int and not a byte.
Here's how
you should properly read a file:
Or a bit shorter:
I'd also like to advise you to:
1) Use a Reader instead of an InputStream. Your code will only properly handle ASCII files.
2) Use a BufferedReader (or BufferedInputStream) to improve performance.
3) Close your streams when you're done with them (in a try-finally construct, or preferably try-with-resources).