Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 824
Savvas Dalkitsis Avatar asked Mar 12 '10 16:03

Savvas Dalkitsis


People also ask

How do I run a .bat file in Java?

Runtime; Process run = Runtime. getRuntime(). exec("cmd.exe", "/c", "Start", "path of the bat file"); This will work for you and is easy to use.

Is BAT and batch file same?

BAT is the batch file that is used in DOS, OS/2 and Microsoft Windows. CMD files are newer version came into existence for batch files. The older systems will not know about CMD files and will run them partially which will throw an error for the batch files saved as CMD.


1 Answers

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
like image 107
Michael Myers Avatar answered Oct 06 '22 08:10

Michael Myers