Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Executing a Windows batch file from Java program

807607Nov 26 2006 — edited Nov 26 2006
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 24 2006
Added on Nov 26 2006
6 comments
1,336 views