Hi forum,
I am attempting to execute a windows batch file from a Java program. The batch file essentially creates a PostGre database and tables and calls an sql script file for the same.
The basic code is:
//Prepare the command for executing the batch file
String[] command =
{"cmd", "/c", "start", CREATE_PRODUCT_WIN_PATH, postGreUser,
aDBName, sqlFilePath, aProductName, currentDate, postGreBin,
postGreHostIP, postGrePort
};
try
{
Process p = Runtime.getRuntime().exec(command, null, null);
int retCode = p.waitFor();
if (0 != retCode)
{
//Log the error
//Do something
}
}
catch (IOException e)
{
//Log the exception
//Do something
}
catch (InterruptedException ie)
{
//Log the exception
//Do something
}
Everything works fine, and the database and tables are created/ initialized properly. But I am not able to get the proper return code in the line that is marked in
bold. The return code what I am getting is the return code of opening a command prompt (which is usually a success, i.e. 0). What I really want is the return code of the batch file. This issue is probably because Windows spawns child processes (in this case, it is the cmd.exe command interpreter) in a detached mode.
My waitFor() waits until the command prompt is opened. Then it returns to the calling thread and executes the script parallelly. Can anyone tell me how to run the batch file in the same thread, so that the waitFor() method returns the exit code of the batch file. Also, is it possible to execute a windows batch file in some other way (other than opening a command prompt)?
Thanks in advance.
Regards,
Kumar.