Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a jar File from java program

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.

like image 368
adesh singh Avatar asked Aug 01 '13 03:08

adesh singh


1 Answers

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);
like image 52
Aniket Thakur Avatar answered Oct 02 '22 11:10

Aniket Thakur