Issue
I need to run executable jar from java fx application. I am trying with following code :
public void runJar() {
try {
//String serverIp = oRMIServer.getServerIP();
String arg1 = "\"arg1\"";
String arg2 = "\"arg2\"";
String command = "java -jar " + "path/of/jar.jar " + arg1 + " " + arg2;
Runtime run = Runtime.getRuntime();
Process proc = run.exec(command);
} catch (Exception e) {
System.out.println("Exception occured "+e);
}
Surprisingly its running in my eclipse if I am creating a new class and writing this code, but frm my Java FX application this code is not running at all. I am not able to see anything looks ike it got skipped. Can someone please help on how to execute java executable jar with args from Java FX application.
Although I've used now
String command = "cmd /c start \"\" \"" + classPath + "\\jre\\bin\\javaw.exe\" -jar \"" + classPath + "\\jarName.jar\" " + runTimeArg1 + " " + runTimeArg2;
Runtime run = Runtime.getRuntime();
Process proc = run.exec(command);
After this also nothing is coming up. Please help!
Solution
Make sure your code is run in try catch and print the stack trace. You should use the String[] command
so that string concatenation is not used and call with ProcessBuilder
so that you can see STDOUT/ERR of your subprocess. Here is an example:
try {
String java = Path.of(System.getProperty("java.home"),"bin", "javaw.exe").toAbsolutePath().toString();
String[] command = new String[] {java, "-jar", "\\path\\to\\yourName.jar", "runTimeArg1", "runTimeArg2"};
exec(command); // or Runtime.getRuntime().exec(command);
} catch (Exception e) {
System.out.println("Exception occurred "+e);
e.printStackTrace();
}
public static int exec(String[] cmd) throws InterruptedException, IOException
{
System.out.println("exec "+Arrays.toString(cmd));
ProcessBuilder pb = new ProcessBuilder(cmd);
Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
pb.redirectOutput(out.toFile());
pb.redirectError(err.toFile());
// OR pb.redirectErrorStream(true);
Process p = pb.start();
long pid = p.pid();
System.out.println("started PID "+pid);
int rc = p.waitFor();
System.out.println("Exit PID "+pid+": RC "+rc +" => "+(rc == 0 ? "OK": "**** ERROR ****"));
System.out.println("STDOUT: \""+Files.readString(out)+'"');
System.out.println("STDERR: \""+Files.readString(err)+'"');
System.out.println();
return rc;
}
Answered By - DuncG