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

}

}

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top