Reputation: 10641
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?
Upvotes: 4
Views: 5421
Reputation: 361
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
Upvotes: 0
Reputation: 6928
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.
Upvotes: 1
Reputation: 66661
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.
Upvotes: 9
Reputation: 4590
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.
Upvotes: 4