Reputation: 1446
I have 2 methods I wrote to try and execute a Jar file from my Java application and they both are not doing anything. The Java Runtime Environment is installed on the C: drive and by default its Path points to a directory on the C: drive. The Jar file I am trying to execute is located on the E: drive.
Jar location: E:\Demo Folder\MyDemo.jar
I tried to execute MyDemo.jar using the following 2 methods:
Method 1:
try {
Runtime.getRuntime().exec("cmd /c start %SystemDrive%\\java -jar " + "E:/Demo Folder/MyDemo.jar");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
Method 2:
try {
File dirFile = new File("E:/Demo Folder/");
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "E:/Demo Folder/MyDemo.jar");
pb.directory(dirFile);
Process p = pb.start();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
Upvotes: 0
Views: 1163
Reputation: 8405
To launch a external java executable application you must first locate the java.exe file (Which loads the JVM) and pass the argument of -jar to indicate loading of a executable JAR file. In both methods you provided you had minor errors within your code.
In method one:
cmd /c start %SystemDrive%\\java -jar
%SystemDrive% is being treated as a string literal as java is unaware of Windows specific environment variables.
In method two:
"java", "-jar", "E:/Demo Folder/MyDemo.jar"
You are assuming that java.exe has been added to PATH environmental variables which may not be the case. Also, from your usage of the "%" operators, I am assuming you are on a windows machine, which uses \ for directories therefore... "E:/Demo Folder/MyDemo.jar" may not return a valid location.
Try the following segment of code:
try {
File dirFile = new File("E:\\Demo Folder\\");
ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java", "-jar", new File(dirFile, "MyDemo.jar").getAbsolutePath());
pb.directory(dirFile);
Process p = pb.start();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
Upvotes: 1
Reputation: 2020
I'm guessing the problem is the space in the path of the jar file. Try this:
new ProcessBuilder("java", "-jar", "\"E:/Demo Folder/MyDemo.jar\"");
Upvotes: 1
Reputation: 75896
Didn't you try to put your invocation logic inside a, say, E:/Demo Folder/rundemo.bat` (or .cmd) file, and call that .bat from your java instead? That's usually more sane and easy to troubleshoot.
Upvotes: 1