如何重新启动 Java 应用程序? [英] How can I restart a Java application?
本文介绍了如何重新启动 Java 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何重新启动 Java AWT 应用程序?我有一个按钮,我附加了一个事件处理程序.我应该使用什么代码来重新启动应用程序?
How can I restart a Java AWT application? I have a button to which I have attached an event handler. What code should I use to restart the application?
我想做与 Application.Restart()
在 C# 应用程序中所做的相同的事情.
I want to do the same thing that Application.Restart()
do in a C# application.
推荐答案
当然可以重新启动 Java 应用程序.
Of course it is possible to restart a Java application.
以下方法显示了一种重新启动 Java 应用程序的方法:
The following method shows a way to restart a Java application:
public void restartApplication()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
}
基本上它执行以下操作:
Basically it does the following:
- 找到 java 可执行文件(我在这里使用了 java 二进制文件,但这取决于您的要求)
- 找到应用程序(在我的例子中是一个 jar,使用
MyClassInTheJar
类来查找 jar 位置本身) - 构建一个命令来重新启动 jar(在本例中使用 java 二进制文件)
- 执行它!(从而终止当前应用程序并重新启动它)
- Find the java executable (I used the java binary here, but that depends on your requirements)
- Find the application (a jar in my case, using the
MyClassInTheJar
class to find the jar location itself) - Build a command to restart the jar (using the java binary in this case)
- Execute it! (and thus terminating the current application and starting it again)
这篇关于如何重新启动 Java 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文