Question

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

}

}

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top