Reputation: 61
in my program i am using r.exec(); to start the command prompt and execute a bat file in it.
But what happens is, as soon as the above statement is executed cmd prompt starts and executes the bat file in it.However, the java program execution will not wait until the bat file is executed in the prompt ie. It starts the cmd prompt & starts executing the bat file in it and continues with the execution of next statements after r.exec();.(Meanwhile my bat file is still being executed in the prompt)
My requirement is that, java program must wait until the bat file in command prompt is executed rather than continuing with the execution of next statements.
Upvotes: 1
Views: 445
Reputation: 1438
r.exec("command")
returns Process
. From here you can simply put the following:
Process process = r.exec("command here");
process.waitFor(); //Waits until process closes
The waitFor()
method will pause this current thread until the process has closed.
Javadoc
waitFor()
: Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated
Further more, if you want to capture input or send commands to the console, you could use process.getInputStream()
and process.getOutputStream()
in separate threads. This would let you monitor the batch file as it runs, so you could cancel terminate process if it breaks down for some reason.
Upvotes: 0
Reputation: 5558
Runtime.exec
returns a Process
instance. On that instance you can call waitFor()
to wait for the Process to complete.
In addition you need to handle Process.getErrorStream()
and Process.getOutputStream()
(usually in a separate Thread) so the Process will not block when these Buffers fill up. ProcessBuilder
with redirectErrorStream(true)
has a handy method that removes the need to handle two streams at once and therfor the additional thread.
Upvotes: 0