Martin Erlic
Martin Erlic

Reputation: 5665

Executing commands using Java Runtime

I was successfully using AutoIt to execute commands but I was thinking I could get a more stable implementation via Runtime. That way I know the commands will always be executed and won't get thrown by Interruption exceptions, and other random crap. Is there something about Runtime that I don't know which won't allow for continuous execution of commands? Does it not have a memory for the outputs of previous commands, i.e. is it not running in a persistent command line?

The following commands navigate to a folder and execute a Maven script. How would I get this to work? If there were 10+ more commands that follow, would they execute within in the same process?

sendCommand("cmd.exe cd homepath/plugins");
sendCommand("mvn archetype:generate -DarchetypeCatalog=file://homepath/.m2/repository");

private static void sendCommand(String text) throws IOException {
    Runtime.getRuntime().exec(text);
}

Upvotes: 0

Views: 710

Answers (2)

Brian
Brian

Reputation: 17309

A few things.

  1. You should use Process and ProcessBuilder instead.
  2. The commands have to be split up and tokenized according to arguments.
  3. The way you have it written, those two commands will not be executed in the same process.
  4. Fortunately for you, ProcessBuilder supports changing the working directory of the command anyway.

As an example:

sendCommand("homepath/plugins", "mvn", "archetype:generate", "-DarchetypeCatalog=file://homepath/.m2/repository");

private static void sendCommand(String workingDirectory, String... command) throws IOException {
    Process proc = new ProcessBuilder(command).directory(new File(workingDirectory)).start();
    int status = proc.waitFor();
    if (status != 0) {
        // Handle non-zero exit code, which means the command failed
    }
}

Notice how a) the command has been split up, and b) that the working directory is passed in and set using ProcessBuilder.directory(File). This will get your desired behavior, but note that each command will still be a separate process, and there's no way to combine them with Java. You'd have to use Maven's features to get them all to run at once by specifying multiple build targets.

Upvotes: 1

Zefick
Zefick

Reputation: 2119

Runtime.exec() returns a Process instance. Call waitFor() on this object to wait until it is complete before running a next command. You can communicate with a Process via its getInputStream()/getOutputStream() methods.

Also read the Javadoc. For Runtime.exec it says "Executes the specified string command in a separate process."

Upvotes: 2

Related Questions