Question

I want to run the following shell command from a java application:

java -jar saxon9he.jar -warnings:fatal a.xml a.xsl param1=123 param2=abc

Currently, I am simply executing this as a shell command using

ProcessBuilder pb = new ProcessBuilder(commandLineParts);
[...]
Process process = pb.start();

What is the correct way to do this in java?

Was it helpful?

Solution

This is the correct way of executing a command in Java. Just to clear possible confusion: ProcessBuilder doesn't execute the program using a shell. That's the reason why you have to provide it with a list of arguments and not a single string (that would be parsed by a shell).

There are two possibilities:

  • either you want to run the Java program in a new JVM and then using the ProcessBuilder is the way to go
  • or you don't mind if it is executed in the same JVM and then you can call the main method yourself as Sean suggests (possibly in a different thread)

Another option, depending on the type of the application, would be to perform some acrobatics with an application server to start the app in it.

If you use the ProcessBuilder just be careful about handling its input and output streams - if you don't handle them your application can hang: Java ProcessBuilder: Input/Output Stream This has been improved in Java 7.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top