Run a jar File from java program

后端 未结 3 2042
臣服心动
臣服心动 2020-12-01 17:50

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

      try {
          Runtime runtime = Runtime.getRuntime();
           


        
相关标签:
3条回答
  • 2020-12-01 18:09

    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.

    0 讨论(0)
  • 2020-12-01 18:10

    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);
    
    0 讨论(0)
  • 2020-12-01 18:16

    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);
    
    0 讨论(0)
提交回复
热议问题