Skip to content
Advertisement

How to send a valid result of an arithmetic operation through DataOutputStream

I have a subprocess class that calculate the sum of two integers and then put it in a DataOutputStream:

public class SubProcess {
  public static void main(String[] args) throws IOException {
     DataInputStream in = new DataInputStream(System.in);
     DataOutputStream out = new DataOutputStream(System.out);
     int a = in.readInt();
     out.writeInt(a);
     int b = in.readInt();
     out.writeInt(b);
     int result = a+b;
     out.writeInt(result);
     out.flush();
     in.read();
     out.close();
     in.close();
    }
  } 

when writing the two values of a and b like 12 and 47 respectivley the result is “ei”.

In another hand the mainprocess won’t read that result like an DataInputStream through the ReadInt() line, and it throws an exception :

        Exception in thread "main" java.io.EOFException
            at java.io.DataInputStream.readInt(Unknown Source)
            at testthread.MainProcess.main(MainProcess.java:21)

Answer

It seems that the main process doesn’t communicate really with the subprocess. deleting the package from the two classes and running the main process on cmd avoid the exception.

Advertisement