eatonphil
eatonphil

Reputation: 13672

executing two commands with process builder

I'm trying to write a program that compiles another java file from the command prompt. I'm having an issue with it however. At this point, it is successfully executing the first part where it compiles Mocha.java. However, I want it to also execute that file and display what it outputs. It displays nothing. Any suggestions?

    pb = new ProcessBuilder("javac","Mocha.java");
    try {
        Process shell = pb.start();
        OutputStream shellOut = shell.getOutputStream();
        shellOut.write("java Mocha".getBytes());
        shellOut.close();
        InputStream shellIn = shell.getInputStream();
        String response = IOUtils.toString(shellIn, "UTF-8");
        System.out.println(response);
        shellIn.close();
        shell.destroy();
    } catch (IOException ex) {
        System.out.println("failed");
    }

Note:

I also tried to have all arguments initally like so:

pb = new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");

But not only did this not work, it did not even compile Mocha.java as it did above.

Thanks!

EDIT:

So I changed this to make two processes. Works great now guys! For anyone interested:

    pb = new ProcessBuilder("javac","Mocha.java");
    try {
        Process shell = pb.start();
        int error = shell.waitFor();
        shell.destroy();
        if (error == 0)
        {
            pb = new ProcessBuilder("java","Mocha");
            shell = pb.start();
            InputStream shellIn = shell.getInputStream();
            String response = IOUtils.toString(shellIn, "UTF-8");
            System.out.println(response);
            shellIn.close();
            shell.destroy();
        }
    } catch (IOException ex) {
        System.out.println("failed");
    } catch (InterruptedException ex) {
    }

Upvotes: 1

Views: 9787

Answers (2)

fge
fge

Reputation: 121702

This is normal: two commands mean two processes. You need two ProcessBuilders, and check the return value of the first process before executing the second one.

This syntax:

new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");

does not work. && is a logical shell operator, the javac command does not understand it. Do your processing logic in Java directly instead:

if (p1.waitFor() == 0) // compile succeeded
    // initiate second process

Upvotes: 3

Jayan
Jayan

Reputation: 18459

The syntax mentioned works with shell, not with java ProcessBuilder.

Option one is to launch shell and execute shell command. Another is to invoke to ProcessBuilder two times. One for javac another for java

Upvotes: 1

Related Questions