0

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?

tomsv
  • 7,207
  • 6
  • 55
  • 88
  • 4
    There is always the option to put the jar on your classpath and call the main method programmatically. – Sean Patrick Floyd Jan 24 '14 at 12:50
  • The main method being defined in META-INF/MANIFEST.MF; open jar with 7zip or so. – Joop Eggen Jan 24 '14 at 12:52
  • What do you think is *incorrect* about using `ProcessBuilder`? – Raedwald Jan 24 '14 at 13:03
  • @SeanPatrickFloyd If you call main, it won't be another process (sometimes this is desired, sometimes not). Process builder forks a new process (but one could also use `Runtime.exec()`). @OP: `ProcessBuilder` is the current practice, but sometimes you must fall back to `Runtime.exec()` when nasty parametrization is involved (e.g., groups with `"`). – rlegendi Jan 24 '14 at 14:00

1 Answers1

4

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.

Community
  • 1
  • 1
Jakub Kotowski
  • 7,411
  • 29
  • 38