4

I am trying the following code using the DataOutputStream. The OutputStream passed to the DataOutputStream is not printing anything. Please see my below code and pllease tell me anything wrong in this code.

public class DataStreamsExample {
public static void main(String[] args) throws IOException {
    DataInputStream dis = new DataInputStream(System.in);
    System.out.println("Enter the First Number");
    int i = dis.readInt();
    System.out.println("Enter the Second Numebr");
    int j= dis.readInt();
    int total = i+j;
    DataOutputStream dos = new DataOutputStream(System.out);
    dos.writeInt(total);

}

}

Sivaranjani D
  • 512
  • 4
  • 16
  • DataInput as the name suggests is for binary data not text. This means unless you *really* know what you are doing, you won't be able to type a binary number in. I suggest you use text such as Scanner and PrintWriter instead. – Peter Lawrey Mar 30 '14 at 15:41

2 Answers2

2

Why are you using data output streams? Can't you use a Scanner for reading input?

Calling dos.flush() will print out your result though.

Arrem
  • 1,005
  • 9
  • 10
1

OutputStream is fundamentally a binary construct. If you want to write text data (e.g. from the console) you should use a Writer of some description. To convert an OutputStream into a Writer, use OutputStreamWriter. Then create a PrintWriter around the Writer, and you can read a line using PrintWriter.println(). You can replace follow line

DataOutputStream out = new DataOutputStream(out);

into this

PrintWriter out = new PrintWriter(new OutputStreamWriter(out));

The character encoding can then be explicitly specified in the constructor of OutputStreamWriter.