2

I want to execute a Java CLI-program from within another Java program and get the output of the CLI-program. I've tried two different implementations (using runtime.exec() and ProcessBuilder) and they don't quite work.

Here's the peculiar part; the implementations work (catch the output) for when executing commands such as pwd but for some reason they do not catch the output of a Hello World java program executed with java Hello.

Execution code:

public static void executeCommand(String command)
{
    System.out.println("Command: \"" + command + "\"");

    Runtime runtime = Runtime.getRuntime();
    try
    {
        Process process = runtime.exec(command);

        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(process.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(process.getErrorStream()));

        // read the output from the command
        System.out.println("Standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

Example output

Command: "cd /Users/axelkennedal/Desktop && java Hello"
Standard output of the command:

Standard error of the command (if any):

Command: "pwd"
Standard output of the command:

/Users/axelkennedal/Dropbox/Programmering/Java/JavaFX/Kode
Standard error of the command (if any):

I have verified that Hello does indeed print "Hello world" to the CLI when running Hello directly from the CLI instead of via executeCommand().

Hello world

public class Hello
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!");
    }
}
7
  • Does Runtime.exec pass the command through a shell? I don't think so, but your command needs to be interpreted by the shell to handle &&. Commented Oct 31, 2015 at 17:38
  • Aha! Any idea on how I would go about doing that? Commented Oct 31, 2015 at 17:41
  • Yes. It's been a long time since I've used Runtime.exec, but I'm pretty sure it doesn't do any command parsing or invoke a shell first. Being pwd is just the command with no arguments it works, but your first command has arguments and needs to be interpreted by the shell. Commented Oct 31, 2015 at 17:43
  • Thanks for the insight, I do believe seeing somewhere that ProcessBuilder on the other hand can handle things like && Commented Oct 31, 2015 at 17:45
  • I don't see that offhand in the ProcessBuilder javadocs, but I might be missing it. In this particular case, Runtime.exec(new String[]{"java", "Hello"}, null, "/Users/axelkennedal/Desktop") would probably work. Commented Oct 31, 2015 at 17:49

1 Answer 1

1

This "cd /Users/axelkennedal/Desktop && java Hello" is not one command but two commands separated by the &&. In general it means do the first command and if the first command succeeds do the second command. You can't pass this as a single command but you can implement the logic yourself:

eg to execute "cmd1 && cmd2"

if (Runtime.getRuntime().exec("cmd1").waitFor() == 0) {
    Runtime.getRuntime().exec("cmd2").waitFor();
}

However, because in this case cmd1 is to change directories there is a better way, which is to use the directory function of ProcessBuilder instead of the first command.

Process p = new ProcessBuilder("java","hello")
        .directory(new File("/Users/axelkennedal/Desktop"))
        .start();
Sign up to request clarification or add additional context in comments.

1 Comment

I just found that in the documentation, which is great :D Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.