Versions Compared

Key

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

The write() method, defined in the class java.io.OutputStream, takes an argument of type int intended to be between 0 and the value of which must be in the range 0 to 255. Because a value of type int could be outside this range, failure to range check can result in the truncation of the higher-order bits of the inputargument.

Wiki Markup
The general contract for the {{write()}} method says that it writes one byte to the output stream. The byte to be written constitutes the eight lower-order bits of the argument {{b}}, passed to the {{write()}} method; the 24 high-order bits of {{b}} are ignored (see \[[API 2006|AA. Bibliography#API 06]\] [{{java.io.OutputStream.write()}}|http://download.oracle.com/javase/6/docs/api/java/io/OutputStream.html#write(int)] for more information).

...

Compliant Solution (Range-Check Inputs)

Perform range checking to be compliant. This compliant solution prints the corresponding character only if the input integer is in the proper range. If the input is outside the representable range of an int, the Integer.valueOf() method throws a NumberFormatException. If the input can be represented by an int but is outside the range required by write(), this code throws an ArithmeticException.

...

This compliant solution uses the writeInt() method of the DataOutputStream class, which can handle output the entire range of values representable as an int.

Code Block
bgColor#ccccff
class FileWrite {
  public static void main(String[] args)
                          throws NumberFormatException, IOException { 
    DataOutputStream dos = new DataOutputStream(System.out);
    dos.writeInt(Integer.valueOf(args[0].toString()));
    System.out.flush(); 
  }     
}

...

Using the write() method to output integers writes only the low-order 8 bits of the integers. This truncation can result in unexpected valuesoutside the range 0 to 255 will result in truncation.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO09-J

low

unlikely

medium

P2

L3

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d5d6fbfb38694fcc-4518e997-43af4260-8bbd8b71-ea28fa55a52f9d63884f72cf"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

[Method write()

http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html#write(int)]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="49dca7787ed68201-5ac9f032-4a9049e1-862caf93-6470b3f8df324131ed743f9e"><ac:plain-text-body><![CDATA[

[[Harold 1999

AA. Bibliography#Harold 99]]

 

]]></ac:plain-text-body></ac:structured-macro>

...