简体   繁体   English

在关闭Java应用程序时运行.bat文件

[英]Run a .bat file on closing java app

I want to run a .bat file when I close my Java application. 关闭Java应用程序时,我想运行.bat文件。

I try, but when I close Java app the bat file doesn't start. 我尝试过,但是当我关闭Java应用程序时,bat文件无法启动。

You might want to look into shutdown hooks. 您可能需要研究关闭挂钩。 Basically you can register an unstarted thread, it will be started by the JVM when the exit process is started. 基本上,您可以注册一个未启动的线程,当退出过程启动时,它将由JVM启动。

Runtime.getRuntime().addShutdownHook(thread)

According to the doc: 根据文档:

The Java virtual machine shuts down in response to two kinds of events: Java虚拟机将响应以下两种事件而关闭:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or 当最后一个非守护线程退出时,或者调用exit(等效于System.exit)方法时,程序将正常退出,或者
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown. 响应于用户中断(例如键入^ C)或系统范围的事件(例如用户注销或系统关闭)来终止虚拟机。

I can think of two options. 我可以想到两个选择。

  1. Start your Java application from within one batch file or ant file, and then have this automatically run another when you finish. 从一个批处理文件或ant文件中启动Java应用程序,然后在完成后自动运行另一个。
  2. Intercept when your application closes using java code, then start a batch file running from Java as a subprocess. 当您的应用程序使用Java代码关闭时进行拦截,然后启动从Java运行的批处理文件作为子进程。 You will probably need to use windows specific methods to keep it running after you exit, if you don't want to keep your application waiting around. 如果您不想让应用程序一直等待,则可能需要使用Windows特定的方法来使其退出后继续运行。

Only 1 will work if your process is killed. 如果您的进程被终止,则只有1个有效。 How are you trying to do it at the moment, and how is it failing? 您目前如何尝试这样做,怎么会失败? Without this information we can't help you. 没有这些信息,我们将无法为您提供帮助。

Please go through this http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html . 请浏览此http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html Use Runtime.getRuntime().addShutdownHook(thread) to associate it. 使用Runtime.getRuntime()。addShutdownHook(thread)进行关联。

如果您的应用程序是扩展SingleFrameApplication的桌面应用程序,则可以覆盖其退出方法: public void exit(EventObject event)并添加代码以在此处启动文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM