views:

973

answers:

5

I am using the following code to execute a batch file:

java.lang.Runtime rt = java.lang.Runtime.getRuntime();
Process pr = rt.exec("MyBatch.bat");

My batch file takes some time to execute. I want my servlet process to wait till the batch file execution completes. I would like to close the command prompt after executing the batch file. How can I do this?

A: 

Look at the documentation for the Process class.

Hemal Pandya
Wow. -1 because I asked the poster to do some work on his own?
Hemal Pandya
+3  A: 

The most straightforward way would be to use the .waitFor() method of the process object you created: pr.waitFor();

This is a blocking call, meaning that no other code will be executed before this call returns.

Mike
+8  A: 

Use Process.waitFor() to have your thread wait for the completion of the batch file's execution.

java.lang.Runtime rt = java.lang.Runtime.getRuntime();
Process pr = rt.exec("MyBatch.bat");
pr.waitFor();

You may also want to look at using ProcessBuilder instead of Runtime.getRuntime().exec() if you need access to the console's output and/or input.

vladr
+1  A: 

As others have said, you can use Process.waitFor(). However, before doing this you must start another thread that continually reads the contents of the process's output and error streams; otherwise if there is an error that causes lots of output your application will hang.

Alternatively you can have your batch file redirect output and errors to a file.

Andrew Duffy
A: 

hi,

You can trace the InputStreamReader from your process. and trace for the lines inside bat file.

When you are EOF then exit from command line

see the Example or full source code. click here

prashant