Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

Run bat file in Java and wait

You would think that launching a bat file from Java would be an easy task but no... I have a bat file that does some sql commands for a loop of values read from a text file. It is more or less like this:

FOR /F %%x in (%CD%\listOfThings.txt) do sqlcmd -Slocalhost\MSSQL %1 %2 -d %3 -i %CD%\SQLScripts\\%%x
exit

Don't worry about the specifics they are not important. What i want is to simply run this bat file from within Java and have it wait until execution is finished. Apparently it is not easy. What i have so far is this:

Runtime.getRuntime().exec("cmd /K start SQLScriptsToRun.bat"
                    +" -U"+getUser()
                    +" -P"+getPass()
                    +" " + projectName);
return true;

The problem is that the exec() method returns immediately. The bat file runs for a good 2-3 minutes. I tried removing the start but to no avail. I tried many variations but it got me nowhere. Any ideas on how to do this simple task?

Upvotes: 6

Views: 11438

Answers (2)

Michael Myers
Michael Myers

Reputation: 192035

You should not ignore the return value of .exec(). It gives you a Process object that you can waitFor(), like this:

final Process process = Runtime.getRuntime().exec("blahblahblah");
final int exitVal = process.waitFor();
// if exitVal == 0, the command succeeded

Upvotes: 15

amit kumar
amit kumar

Reputation: 21042

you need to use waitFor on the process exec call returns.

Upvotes: 7

Related Questions