Run the bat file in Java and wait

You think running a bat file with Java will be an easy task, but no ... I have a bat file that executes some sql commands to loop values ​​read from a text file. This is something like this:

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

Do not worry about the specifics in which they are not important. I want to just run this bat file from Java and wait for it to complete. This is apparently not easy. What I still know:

 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 2-3 minutes. I tried to remove the beginning, but to no avail. I have tried many options, but this is of no use. Any ideas on how to do this simple task?

+4
source share
2 answers

You should not ignore the return value of .exec() . It gives you a Process object, which you can waitFor() for example:

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

you need to use waitFor when calling the exec process.

+6
source

Source: https://habr.com/ru/post/1303953/


All Articles