java 如何使用批处理脚本停止正在运行的 *.JAR 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1563029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:06:09  来源:igfitidea点击:

How to stop a running *.JAR file with a batch script?

javabatch-filejar

提问by Faizan S.

We are facing trouble restarting closing a running *.JAR file started with the "java -cp".

我们在重新关闭正在运行的 *.JAR 文件时遇到问题started with the "java -cp"

Killing java.exe worked fine.

杀死 java.exe 工作正常。

But... isn't there any smoother way for the application? (It saves data on shut-down)

但是……难道没有更顺畅的申请方式吗?(它在关机时保存数据)

Also, how can one simulate any key input at the following message "Enter any key to continue..."with a batch file?

另外,如何"Enter any key to continue..."使用批处理文件模拟以下消息中的任何键输入?

Thanks for all help!

感谢所有帮助!

回答by Nirmal Patel

The following set of batch scripts can be used to start/stop jars/any program

以下一组批处理脚本可用于启动/停止 jars/任何程序

start-jar.bat

启动jar.bat

start "win_title" java -jar [jar file] [jar options]

this basically starts your jar(the program) in a window with title set to "win_title".

这基本上会在标题设置为“win_title”的窗口中启动您的 jar(程序)。

you could use another batch to kill the window started

您可以使用另一批来终止窗口启动

stop-jar.bat

停止jar.bat

TASKKILL /FI "WINDOWTITLE eq win_title

回答by Gandalf

Use the PAUSE [message] to wait for a key press:

使用 PAUSE [message] 等待按键:

PAUSE Hit any key to continue..

As for killing your app, there are JMX ways to do it - but I find an easy way to have a socket listening on a local port and then you can easily send a kill commnad to it and let your program handle the shutdown.

至于杀死你的应用程序,有 JMX 方法可以做到这一点 - 但我找到了一种让套接字侦听本地端口的简单方法,然后你可以轻松地向它发送终止命令并让你的程序处理关闭。

回答by Jonathan Feinberg

The excellent Java Service Wrapperwill let you effortlessly install signal handlers for your Java app.

优秀的Java Service Wrapper将让您毫不费力地为您的 Java 应用程序安装信号处理程序。

回答by Roy Tang

Have your app create a temp file on startup and periodically check if it still exists. Your batch script can just delete that file to terminate the app.

让您的应用程序在启动时创建一个临时文件并定期检查它是否仍然存在。您的批处理脚本可以删除该文件以终止应用程序。

回答by akf

If you need to do some cleaning up before your process is shutdown, take a look at Shutdown Hooks.

如果您需要在关闭进程之前进行一些清理,请查看Shutdown Hooks

from the Q&A in the link:

来自链接中的问答:

Okay, but won't I have to write a lot of code just to register a simple shutdown hook?

No. Simple shutdown hooks can often be written as anonymous inner classes, as in this example:

好的,但是我不需要编写大量代码来注册一个简单的关闭挂钩吗?

不。简单的关闭钩子通常可以写成匿名内部类,如下例所示:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { database.close(); }
});