Run a jar File from java program

会有一股神秘感。 提交于 2019-11-26 23:10:48

问题


I am trying to execute jar files from another Java program. I am using the following code :

      try {
          Runtime runtime = Runtime.getRuntime();
          runtime.exec("path upto jar");
      } catch (Exception ex) {
          JOptionPane.showMessageDialog(null, "Exception occured" + ex);
      }

But its not working. I tried google and it gave me the examples using ProcessBuilder, but that is not working either.


回答1:


Using ProcessBuilder(java.lang.ProcessBuilder) will solve your problem. Syntax is as follows -

ProcessBuilder pb = new ProcessBuilder("java", "-jar", "absolute path upto jar");
Process p = pb.start();

You can redirent input/output/error to/from files as follows

File commands = new File("absolute path to inputs file");
File dirOut = new File("absolute path to outputs file");
File dirErr = new File("absolute path to error file");

dirProcess.redirectInput(commands);
dirProcess.redirectOutput(dirOut);
dirProcess.redirectError(dirErr);



回答2:


First suggestion/recommendation is to use ProcessBuilder instead of Runtime. Here is what you can try:

ProcessBuilder pb = new ProcessBuilder("java", "-jar", "./jarpath/yourjar.jar");
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = "";
while((s = in.readLine()) != null){
    System.out.println(s);
}
int status = p.waitFor();
System.out.println("Exited with status: " + status);



回答3:


You can run a jar file from where ever you want by using only this one line code.

    Desktop.getDesktop().open(new File("D:/FormsDesktop.jar"));

where

new File("your path to jar")

Hope it helps.

Thanks.



来源:https://stackoverflow.com/questions/17985036/run-a-jar-file-from-java-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!