-1

I have a program that is supposed to open a different program in c++, which will return 0, 1, 2, or 3. As a test, I made some sample code:

public class Tester {
    public static void main(String[] args) {
        String[] command = {"c:\\Java Prog\\helloWorld.exe"};
        ProcessBuilder proc = new ProcessBuilder(command);
        System.out.println(proc);
    }
}

The C++ Program was simply:

#include <iostream>
using namespace std; // I know, I know, it's bad.
int main(void) {
    return 2;
}

This printed out:

java.lang.ProcessBuilder@1db9742

I was expecting that. However, when I tried to cast the output to an int (or anything else), the compiler (Eclipse Mars) told me that it could not cast from ProcessBuilder to [insert any variable type of your choice here].

What am I doing wrong? Can I format the output to an int? If not, how should I? Thanks in advance

  • err, is that ProcessBuilder ever [start](https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#start())? then you can hook the Process's [output stream](https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getOutputStream()).. – Bagus Tesa May 19 '17 at 01:22
  • 1
    I think [something like this](https://www.google.com.au/search?q=java+processbuilder&oq=java+processbuilder&aqs=chrome..69i57j69i60l2j0l2j69i60.5232j0j7&sourceid=chrome&ie=UTF-8) would be a better starting place for your question – MadProgrammer May 19 '17 at 01:26
  • 1
    So you expected the output you got, but you thought you could somehow cast it to an int? That's surprising... – shmosel May 19 '17 at 02:45
  • Hasn't anybody here read the code in the question? The value is *returned*, from `main()`, not *output* via `stdout` or `stderr`. It is therefore available as an **exit code**. READ THE QUESTION!!! – user207421 May 19 '17 at 04:16
  • Erm. Creating a process builder and actually executing it are two separate operations. I won't downvote you, but try to keep learning how process execution works before posting such questions. – Arunav Sanyal May 19 '17 at 04:20

1 Answers1

0

How do I get int output from ProcessBuilder in Java?

You don't. You get it from the Process.

Everything is missing here. You haven't even executed the process, let alone done anything sensible about getting its return value.

You need to:

  1. Create and start the Process.
  2. Close its input stream and consume both its output streams. In this particular case there is no input or output so it doesn't matter, but in the general case there is.
  3. Get the Process.exitValue().
user207421
  • 305,947
  • 44
  • 307
  • 483