我为我的游戏编写了一个启动程序,当给定有效的用户名和密码时,将从网站下载JAR文件(如果该文件尚不存在或有更新可用)。登录系统和文件下载工作,但我如何运行下载的JAR文件?我试过Runtime.getRuntime().exec("java -jar " + file.getAbsolutePath());
,但无济于事。执行外部JAR
感谢您的帮助!
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蜘蛛的任何提示?
为什么不加载它并在内部运行?否则,总是使用'String []'方法并分开参数,考虑使用'ProcessBuilder'。 – 2013-04-26 22:08:19