我爲我的遊戲編寫了一個啓動程序,當給定有效的用戶名和密碼時,將從網站下載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