Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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

...

method reads a single byte from an input source, and returns its value as an int, in the range 0 to 255.

...

It will return -1 only if the end of the input stream has been reached. The similar Reader.read() method reads a single character,

...

and returns its value as an int, in the ragen 0-65,535. It also returns -1 only if the end of the stream

...

has been reached. Both methods are meant to be overridden by subclasses.

These methods are 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 bitsor char from a stream. Unfortunately many programmers eagerly convert the resulting int back to a byte or char before checking the value for -1. It is vital to check that read() did not return the return value for -1 before narrowing the return value it to a byte or char.

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

...

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

...

This noncompliant code example casts the value of type int returned by the read() method directly to a value of type char, which is then compared with -1 in an attempt to detect the end of stream. This conversion leaves the value of c as 0xffff (Character.MAX_VALUE) instead of -1. As a result, the test for the end of stream never evaluates to true.

Code Block
bgColor#FFcccc

FileReader in;
// initialize stream 
char c;
while ((c = (char) in.read()) != -1) { 
  // ... 
}

...

Use and value of type int to capture the return value of the character input method. When the value of returned by read() is not -1, it can be safely cast to type char.

Code Block
bgColor#ccccff

FileReader in;
// initialize stream 
int inbuff;
char data;
while ((inbuff = in.read()) != -1) { 
  data = (char) inbuff;
  // ...  
}

...