gpt4 book ai didi

java - 执行外部 JAR

转载 作者:行者123 更新时间:2023-11-30 07:17:23 24 4
gpt4 key购买 nike

我为我的游戏编写了一个启动器,当提供有效的用户名和密码时,如果该文件不存在或有更新可用,它将从网站下载 JAR 文件。登录系统和文件下载工作正常,但如何运行下载的 JAR 文件?

我试过 Runtime.getRuntime().exec("java -jar "+ file.getAbsolutePath());,但无济于事。

感谢您的帮助!


downloading = new JLabel("Download AudioRPG executable from server. This may take up to a minute.");
downloading.setHorizontalAlignment(SwingConstants.CENTER);

Thread th = new Thread(new Runnable() {
public void run() {
remove(username);
remove(password);
remove(submit);
remove(remember);
add(downloading, BorderLayout.CENTER);
pack();

try {
FTPClient client = new FTPClient();

client.connect("audiorpg.net");
client.login("audiorpg", "mcpogotime1");
client.changeDirectory("files");
client.download("AudioRPG.jar", exe);
client.disconnect(true);
downloading.setText("Done! Launching AudioRPG...");
}
catch (Exception e) { e.printStackTrace(); }
}
});

th.start();

startExternalJAR(getClass(), th, exe);

private static void startExternalJAR(Class<?> c, Thread th, File exe) {
if (!th.isAlive()) {
try {
final String mainClass;
final JarFile jarFile = new JarFile(exe);
try {
final Manifest manifest = jarFile.getManifest();
mainClass = manifest.getMainAttributes().getValue("Main-Class");
} finally {
jarFile.close();
}
final URLClassLoader child = new URLClassLoader(new URL[]{exe.toURI().toURL()}, c.getClassLoader());
final Class<?> classToLoad = Class.forName(mainClass, true, child);
final Method method = classToLoad.getDeclaredMethod("main", String[].class);
final Object[] arguments = {new String[0]};
method.invoke(null, arguments);
}
catch (Exception ex) { ex.printStackTrace(); }
}
else {
try { Thread.sleep(1000); }
catch (Exception e) { }
startExternalJAR(c, th, exe);
}
}

这是我现在尝试使用的代码,但它不起作用。 @Boris the Spider 有什么建议吗?

最佳答案

不要像命令一样执行jar。使用类加载器从 jar 中加载所需的类,然后实例化它。

http://docs.oracle.com/javase/tutorial/deployment/jar/jarclassloader.html

  1. 通过构造一个 new JarClassLoader("url goes here") 加载 jar。
  2. 在 JarClassLoader 上调用 .invokeClass("MyMainClassName", new String[] { "Args", "Go", "Here"})

关于java - 执行外部 JAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16245914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com