Run bat file in Java and wait

10,354

Solution 1

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

Solution 2

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

Share:
10,354
Mohammad Taha
Author by

Mohammad Taha

Android geek, TDD nut, International Speaker, ex Shazamer, currently the Principal Software Engineer for Apps at ASOS. Noti.st | Twitter | LinkedIn | GitHub

Updated on June 14, 2022

Comments

  • Mohammad Taha
    Mohammad Taha almost 2 years

    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?