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 255. Because a value of type int may well be outside of this range, failure to range check may lead to can result in the truncation of the higher order bits of the input.

Wiki Markup
The general contract for the {{write()}} method says that it writes one byte is written 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. \[[API 06|AA. Java References#API 06]\]

Noncompliant Code Example

The This noncompliant code example accepts a value from the user without validating it. Any value with more than eight bits set that is not in the range of 0 to 255 is truncated. For instance, write(303) prints / because the lower order bits of 303 are preserved while the top 24 order bits are lost (303 mod 256 is 47 and / has ASCII code 47). That is, the result is remainder modulo 256 of the absolute value of the input.

...

Alternatively, perform range checking to be compliant. While this particular compliant solution still does not display the original invalid out-of-range integer correctly, it behaves well when the corresponding read() method is used to convert the byte value back to a value of type int. This is because it guarantees that the byte variable will contain representable data.

Code Block
bgColor#ccccff
class FileWrite {
  public static void main(String[] args) throws NumberFormatException, IOException { 
    FileOutputStream  out = new FileOutputStream("output.txt");   

    //Perform range checking  
    if(Integer.valueOf(args[0]) >=< 0 &&|| Integer.valueOf(args[0]) <=> 255) {
      throw new ArithmeticException("Value is out of range");
    }
  
    out.write(Integer.valueOf(args[0].toString()));
      System.out.flush();
    }
    else {
      //handle error 
      throw new ArithmeticException("Value is out of range");
    } 
  }
}

Compliant Solution (3)

In this This compliant solution , uses the writeInt() method of the DataOutputStream class is used.

Code Block
bgColor#ccccff
class FileWrite {
  public static void main(String[] args) throws NumberFormatException, IOException { 
    FileOutputStream  out = new FileOutputStream("output.txt");   
    DataOutputStream dos = new DataOutputStream(out);
    dos.writeInt(Integer.valueOf(args[0].toString()));
    dos.close();
    out.close();// close out and dos 
  }     
}

Risk Assessment

Using the write() method to output integers may result in unexpected values.

...