简体   繁体   中英

Executing a Jar file from an Java application

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());
}

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.

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\"");

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM