Java's Runtime class allows named system property values to be sent as command line arguments when running a jar. Like below:
Runtime.getRuntime().exec("java -jar -DiName=ABC C:\\Test.jar");
I am trying to move from Runtime to ProcessBuilder to achieve the same functionality. Need advice on what the correct way to do this is.
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\Test.jar").start();
In the above code, how can I pass the "iName"?
The reason I am moving from Runtime to ProcessBuilder is, the java program that triggers this Runtime code is not working in a specific production environment which is using 1.8.0_40 JDK.
答案 0 :(得分:1)
Just have a look at the Javadoc.
There it is stated clearly that the ProcessBuilder
Constructor can be of the form public ProcessBuilder(String... command)
(for example, see Timothy Truckle comment) or, equivalently, just a single parameter of type List<String>
.
So opposite to Runtime
, which tokenizes one single String, here the ProcessBuilder
, needs already tokenized parameter list.
Probably, to avoid any future confusion, it would be the best to store the parameters in a variable, for easier modification later. For instance:
List<String> params = java.util.Arrays.asList("java", "-jar", "-DiName=ABC", "C:\\Test.jar");
ProcessBuilder pb = new ProcessBuilder(params).start();
Hope this helps in the long run!
答案 1 :(得分:0)
new ProcessBuilder("java", "-jar", "-DiName=ABC", "C:\\Test.jar");
ProcessBuilder
receives array (varargs) of parameters, which will be concatenated and executed.