如何在 Java Swing 应用程序中引入自动更新和重启功能。我还需要回滚到以前的版本。我制作了一个应用程序 jar 文件和启动器 jar 文件,用于启动应用程序 jar 文件。这次尝试是成功的。但是在为 MacOSX 创建安装程序时,我无法集成这两个 jar 文件。
Launcher class
如下:
public class Launcher {
private final Logger logger = Logger.getLogger(Launcher.class.getName());
private String getVersionNumber() throws IOException {
try {
JarFile runningJarFile = new JarFile(new File("Application.jar"));
String versionNumber = runningJarFile.getManifest()
.getMainAttributes().getValue("Bundle-Version");
runningJarFile.close();
logger.log(
Level.SEVERE,
new StringBuilder()
.append("The version number of existing Application.jar file is ")
.append(versionNumber).toString());
return versionNumber;
} catch (IOException e) {
logger.log(
Level.SEVERE,
new StringBuilder()
.append("Could not read the version number from existing Application.jar")
.append(Arrays.toString(e.getStackTrace()))
.toString());
throw new IOException(e);
}
}
private void updateApplication() {
try {
File updateDirectory = new File("Update");
if (updateDirectory.isDirectory()) {
if (updateDirectory.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("\\.");
}
}).length > 0) {
String versionNumber = getVersionNumber();
logger.log(
Level.SEVERE,
new StringBuilder()
.append("A new update is available. Rename the existing Application.jar to ")
.append(versionNumber)
.append(".jar")
.append(" and rename the new_Application.jar to Application.jar")
.toString());
File Application = new File("Application.jar");
Application.renameTo(new File(new StringBuilder()
.append(versionNumber).append(".jar").toString()));
File newApplication = new File("Update/new_Application.jar");
newApplication.renameTo(new File("Application.jar"));
newApplication.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE,
new StringBuilder().append("Could not update Application")
.append(Arrays.toString(e.getStackTrace()))
.toString());
}
}
private void launchApplication() {
try {
logger.log(Level.SEVERE, "Lauching Application.jar");
ProcessBuilder pb = new ProcessBuilder("Java", "-jar", "Application.jar");
pb.start();
} catch (IOException e) {
logger.log(Level.SEVERE,
new StringBuilder().append("Could not launch Application.jar ")
.append(Arrays.toString(e.getStackTrace()))
.toString());
}
}
private void quitLauncher() {
logger.log(Level.SEVERE, "Launcher is exiting");
System.exit(0);
}
private void startApplication() {
updateApplication();
launchApplication();
quitLauncher();
}
public static void main(String[] args) {
Launcher launcher = new Launcher();
launcher.startApplication();
}
}
谢谢