Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added CS

...

Code Block
bgColor#ccccff
class ConsoleWrite {
  public static void main(String[] args) { 
    System.out.println(args[0]);
  }
}

Compliant Solution (2)

Alternatively, perform input validation. While this particular solution will still not display the integer correctly, it will behave well when the corresponding read method is utilized to convert the byte back to an integer.

Code Block
bgColor#ccccff
class ConsoleWriteFileWrite {
  public static void main(String[] args) throws NumberFormatException, IOException { 
    FileOutputStream  out = new FileOutputStream("output.txt");   
    //Perform input validation
    if(Integer.valueOf(args[0]) >= 0 && Integer.valueOf(args[0]) <= 255) {
    System.  out.write(Integer.valueOf(args[0].toString()));
      System.out.flush();
    }
    else {
      //handle error 
      throw new ArithmeticException("Value is out of range");
    } 
  }
}

Compliant Solution (3)

Similarly, if it is required to write a larger integer value, the writeInt() method of the DataOutputStream class can be used. Again, the output should not be used without appropriately escaping or encoding it.

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();
  }     
}

Risk Assessment

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

...