Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing, rewrote intro

Wiki Markup
The abstract {{InputStream.read()}} method is defined as follows, according to \[[API 2006|AA. Bibliography#API 06]\]:

Reads the next byte of data from the input stream. 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. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

This method is often used to read a byte from an input stream. It is sometimes also used to read a character from the input stream when the character is known to require only 8 bits. Unfortunately many programmers eagerly convert the resulting int to a byte or char before checking the value for -1. It is vital to check that read() did not return -1 before narrowing the return value to a byte or char.

This

Input methods that return a byte or char may also return or -1 if the end of the stream is reached.

In the case of a function that returns a char, these methods return a value of type int so that the end of stream may be indicated by a -1.

In the case of a function that returns a byte, these methods return a value of type int which allows the caller to distinguish between -1 and the byte value 0xFF promoted and sign extended to an int.

In particular, this guideline applies to any InputStream subclass that provide an implementation of this classes' abstract the read() method. This guideline is a specific instances instance of NUM15-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data.

...

Use and value of type int to capture the return value of the byte input method. If the value returned by read() is not -1, it can be safely cast to type byte. If read() returns 0XFF, the comparison will test 0x000000FF against 0xFFFFFFFF and fail.

Code Block
bgColor#ccccff
FileInputStream in;
int inbuff;
byte data;
while ((inbuff = in.read()) != -1) { 
  data = (byte) inbuff;
  // ...  
}

...