...
This noncompliant code example casts the value returned by the read()
method directly to a value of type byte
and then compares this value with -1 in an attempt to detect the end of the stream. This conversion leaves the value of c
as 0xFFFF
(e.g., Character.MAX_VALUE
) instead of -1. Consequently, the test for the end of stream never evaluates to true (because the char
type is unsigned and the value of c
is 0-extended to 0x0000FFFF
).
Code Block | ||
---|---|---|
| ||
FileInputStream in; // initialize stream byte data; while ((data = (byte) in.read()) != -1) { // ... } |
When If the return value of read()
method is cast to the byte
value 0xFF
, the returned byte encounters a 0xFF
byte in the file, this value is indistinguishable from the -1 value used to indicate the end of stream, because the byte value is promoted and sign-extended to an int
before being compared with -1. Consequently, the loop can halt prematurely if a 0xFF
byte is read.
Compliant Solution (byte
)
...
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
data
as 0xFFFF
(e.g., Character.MAX_VALUE
) instead of -1. Consequently, the test for the end of stream file never evaluates to true.
Code Block | ||
---|---|---|
| ||
FileReader in; // initialize stream char cdata; while ((cdata = (char) in.read()) != -1) { // ... } |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="237a704da3ccc0a4-ccae949c-4456452e-a770b477-ed29960e83d178d543818476"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. References#API 06]] | Class | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="938b5fdd199224ce-db087be0-4b6f4580-9a9296c6-eb75a1f8d062ee98ac690638"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. References#JLS 05]] | [§4.2 | http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2] Primitive Types and Values | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f50fdf610c769121-9b9b633f-4dd24c4c-9474b683-c9cd3a7eeef4e53d7792adca"><ac:plain-text-body><![CDATA[ | [[Pugh 2008 | AA. References#Pugh 08]] | Waiting for the End | ]]></ac:plain-text-body></ac:structured-macro> |
...