开发者

How I can be notified when a batch file ran within java ends?

开发者 https://www.devze.com 2023-04-01 03:30 出处:网络
I executed a batch file from within my Java code like below: Runtime.getRuntime().exec(\"cmd /c start update.bat\");

I executed a batch file from within my Java code like below:

Runtime.getRuntime().exec("cmd /c start update.bat");

I want to know whether can I get开发者_运维问答 any notification when this batch script completes. Is it possible?

Regards,

Anand


Keep a reference to the Process and waitFor the process to stop, this will halt your excecution.

 Process proc = Runtime.getRuntime().exec("cmd /c start update.bat");
 int exitVal = proc.waitFor();

Do as the good example in this link (When Runtime.exec() won't). If you read the whole article you will avoid and understand many pitfalls of the exec command.

Then you can read up on ProcessBuilder which is a more modern way to invoke other processes.


Everything you need to know , with code samples .

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html


You can use the default Java ProcessBuilder.

  ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "start", "update.bat");
  builder.start();
  builder.waitFor();

The call to waitFor will block, so you once it returns you know your batch script is done.

Alternatively, you can use the commons-exec jar. This has more options for checking the result and doesn't block your thread. See this example on how it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号