0

I have a set of commands that i am executing through java. I stored them in .bat file and then executing through java. When i run bat file through command prompt it executes but when i execute it through java, only 1-2 commands execute and program exits. Please suggest me the solution for this.

Please suggest me the jar file too if any other command referenced

Code:

public static String cmdExec(String cmd) throws IOException {

        Process p = Runtime.getRuntime().exec(cmd);
}
Rajat Nigam
  • 13
  • 1
  • 6
  • Is it possible to post your .bat file? The Runtime command works as `Runtime.getRuntime().exec("cmd /c start "+ pathToBatFile);` – Nikhil Talreja Jun 20 '14 at 06:11
  • Add a p.waitFor() after the exec. Not sure what happens to the exec'd cmd if the parent process terminates. – laune Jun 20 '14 at 06:18
  • http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html – kaqqao Jun 20 '14 at 14:53

1 Answers1

0

The basic form for executing something should be;

public static String cmdExec(String cmd) throws IOException {
    Process p = Runtime.getRuntime().exec(cmd);
    p-waitFor();
}

There are several circumstances that may affect the execution of the command if one does not wait for its completion.

Only if you are certain that the parent process (i.e. this Java program) continues, no other exec that might interfere with this exec is started, no resource required by this exec is affected, only then omit the waitFor for more efficiency (by parallel execution).

laune
  • 31,114
  • 3
  • 29
  • 42