views:

248

answers:

2

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?

+5  A: 

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

Amit Kumar
thanks it wworked but mmyers beat you by 2 seconds and gave an example :P +1 though
Savvas Dalkitsis
@Savvas: Actually he beat me by 24 seconds, but maybe that was because of the example... :)
Michael Myers
:) i wish i could give you 2+ then :P
Savvas Dalkitsis
+6  A: 

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
Michael Myers
oh my i feel so stupid now. I did not find this when searching... Thanks a lot. Hopefully this thread will help other people like me :P
Savvas Dalkitsis