本文目录导读:

我来为您提供一个完整的Java安装包制作案例,包含详细步骤和代码示例。
项目准备
项目结构
myapp/
├── src/
│ └── com/example/
│ └── MainApplication.java
├── resources/
│ ├── images/
│ └── config/
├── lib/
└── dist/
简单示例程序
// MainApplication.java
package com.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class MainApplication extends JFrame {
public MainApplication() {
setTitle("Java应用程序");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建主面板
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// 添加标签
JLabel label = new JLabel("欢迎使用Java应用!", SwingConstants.CENTER);
label.setFont(new Font("微软雅黑", Font.BOLD, 18));
panel.add(label, BorderLayout.CENTER);
// 添加按钮
JButton button = new JButton("点击我");
button.addActionListener((ActionEvent e) -> {
JOptionPane.showMessageDialog(this, "按钮被点击了!");
});
panel.add(button, BorderLayout.SOUTH);
add(panel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MainApplication().setVisible(true);
});
}
}
使用Maven构建插件(推荐)
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>myapp</finalName>
<plugins>
<!-- 打包可执行Jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.MainApplication</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<!-- 复制依赖到lib目录 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<!-- 生成安装配置 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<descriptors>
<descriptor>src/assembly/package.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Assembly描述文件
<!-- src/assembly/package.xml -->
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0
http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>dist</id>
<formats>
<format>zip</format>
<format>tar.gz</format>
</formats>
<fileSets>
<!-- 包含启动脚本 -->
<fileSet>
<directory>src/scripts</directory>
<outputDirectory>/bin</outputDirectory>
<includes>
<include>*.sh</include>
<include>*.bat</include>
</includes>
<fileMode>0755</fileMode>
</fileSet>
<!-- 包含配置文件 -->
<fileSet>
<directory>src/config</directory>
<outputDirectory>/config</outputDirectory>
</fileSet>
<!-- 包含资源文件 -->
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory>/resources</outputDirectory>
</fileSet>
<!-- 包含主程序 -->
<fileSet>
<directory>${project.build.directory}</directory>
<outputDirectory>/lib</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
<!-- 包含依赖 -->
<fileSet>
<directory>${project.build.directory}/lib</directory>
<outputDirectory>/lib</outputDirectory>
<excludes>
<exclude>myapp.jar</exclude>
</excludes>
</fileSet>
</fileSets>
</assembly>
启动脚本
Linux/Mac启动脚本 (run.sh)
#!/bin/bash
# Java应用启动脚本
APP_NAME="myapp"
APP_HOME="$(cd "$(dirname "$0")/.." && pwd)"
JAVA_OPTS="-Xms256m -Xmx512m"
# 设置JAVA_HOME(如果没有配置)
if [ -z "$JAVA_HOME" ]; then
JAVA_HOME="/usr/lib/jvm/java-11"
fi
# 构建classpath
CP="$APP_HOME/lib/*:$APP_HOME/resources"
# 启动应用
echo "Starting $APP_NAME..."
exec $JAVA_HOME/bin/java $JAVA_OPTS -cp "$CP" com.example.MainApplication "$@"
Windows启动脚本 (run.bat)
@echo off
setlocal
REM Java应用启动脚本
set APP_HOME=%~dp0..
set JAVA_OPTS=-Xms256m -Xmx512m
REM 设置JAVA_HOME(如果没有配置)
if "%JAVA_HOME%"=="" (
set JAVA_HOME=C:\Program Files\Java\jdk-11
)
REM 构建classpath
set CP=%APP_HOME%\lib\*;%APP_HOME%\resources
REM 启动应用
echo Starting myapp...
"%JAVA_HOME%\bin\java" %JAVA_OPTS% -cp "%CP%" com.example.MainApplication %*
endlocal
使用install4j制作专业安装包
安装4j项目配置示例
<?xml version="1.0" encoding="UTF-8"?>
<install4j>
<application name="MyApp"
version="1.0.0"
publisher="My Company">
<screens>
<welcomeScreen/>
<licenseScreen>
<file>licenses/LICENSE.txt</file>
</licenseScreen>
<installationDirectoryScreen/>
<installationTypeScreen/>
<confirmInstallationScreen/>
<finishedScreen/>
</screens>
<launchers>
<launcher name="MyApp" id="custom">
<executableName>myapp</executableName>
<icon>icons/app.ico</icon>
<mainClass>com.example.MainApplication</mainClass>
<splashScreen>
<image>images/splash.png</image>
</splashScreen>
<jreLocation>jre</jreLocation>
<vmOptions>
<option>-Xmx512m</option>
<option>-Dfile.encoding=UTF-8</option>
</vmOptions>
</launcher>
</launchers>
<components>
<component id="application">
<files>
<file>
<source>dist/myapp.jar</source>
<dest>lib/myapp.jar</dest>
</file>
</files>
</component>
</components>
<installerOptions>
<requiredInstallerVersion>5.0</requiredInstallerVersion>
<friendlyName>My Application Installer</friendlyName>
<fileName>myapp-setup</fileName>
<!-- 自动生成快捷方式 -->
<shortcuts>
<shortcut name="MyApp"
shortcutType="desktop_and_start_menu"
launcherId="custom"/>
</shortcuts>
<!-- 关联文件类型 -->
<fileAssociations>
<fileAssociation name="MyApp File"
extensions="myapp"
launcherId="custom"/>
</fileAssociations>
</installerOptions>
</application>
</install4j>
使用JLink构建自定义运行时(Java 9+)
# 1. 构建模块化应用
javac -d mods/com.example $(find src -name "*.java")
# 2. 创建模块描述文件
cat > mods/com.example/module-info.java << EOF
module com.example {
requires java.desktop;
exports com.example;
}
EOF
# 3. 构建自定义JRE
jlink \
--module-path mods:$JAVA_HOME/jmods \
--add-modules com.example,java.desktop \
--output myapp-runtime \
--launcher myapp=com.example/com.example.MainApplication \
--compress=2 \
--strip-debug \
--no-header-files \
--no-man-pages
# 4. 打包分发包
tar -czf myapp-linux-x64.tar.gz myapp-runtime/
# 或使用jpackage(Java 14+)
jpackage \
--input target \
--name MyApp \
--main-jar myapp.jar \
--main-class com.example.MainApplication \
--type app-image \
--icon app.ico \
--vendor "My Company" \
--app-version 1.0.0
配置Windows服务
<!-- 使用WinSW配置Windows服务 -->
<service>
<id>myapp</id>
<name>MyApp Service</name>
<description>Java Application Service</description>
<executable>java</executable>
<arguments>-Xmx512m -jar "%BASE%\lib\myapp.jar"</arguments>
<logmode>rotate</logmode>
</service>
安装脚本示例
Linux安装脚本
#!/bin/bash # 安装Java应用 APP_NAME="myapp" INSTALL_DIR="/opt/$APP_NAME" VERSION="1.0.0" echo "Installing $APP_NAME v$VERSION..." # 创建安装目录 mkdir -p $INSTALL_DIR mkdir -p $INSTALL_DIR/bin mkdir -p $INSTALL_DIR/lib mkdir -p $INSTALL_DIR/config mkdir -p $INSTALL_DIR/logs # 复制文件 cp -r dist/* $INSTALL_DIR/ cp -r config/* $INSTALL_DIR/config/ # 创建启动脚本 cat > /usr/local/bin/myapp << EOF #!/bin/bash exec $INSTALL_DIR/bin/run.sh "\$@" EOF chmod +x /usr/local/bin/myapp # 设置权限 chown -R root:root $INSTALL_DIR chmod -R 755 $INSTALL_DIR echo "Installation completed!" echo "Run 'myapp' to start the application"
Windows安装打包 (NSIS)
; NSIS安装脚本示例
!include "MUI2.nsh"
!define PRODUCT_NAME "Java Application"
!define VERSION "1.0.0"
!define INSTALL_DIR "$PROGRAMFILES\JavaApp"
Name "${PRODUCT_NAME}"
OutFile "JavaAppSetup.exe"
InstallDir "${INSTALL_DIR}"
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_LANGUAGE "SimplifiedChinese"
Section "MainSection" SEC01
SetOutPath "$INSTDIR"
; 复制应用文件
File /r "dist\*"
File /r "config\*"
; 创建开始菜单快捷方式
CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"
CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" \
"$INSTDIR\bin\run.bat"
; 创建桌面快捷方式
CreateShortCut "$DESKTOP\${PRODUCT_NAME}.lnk" \
"$INSTDIR\bin\run.bat"
; 注册卸载信息
WriteUninstaller "$INSTDIR\uninstall.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
"DisplayName" "${PRODUCT_NAME}"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" \
"UninstallString" "$INSTDIR\uninstall.exe"
SectionEnd
Section "Uninstall"
Delete "$INSTDIR\uninstall.exe"
RMDir /r "$INSTDIR"
Delete "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk"
RMDir "$SMPROGRAMS\${PRODUCT_NAME}"
Delete "$DESKTOP\${PRODUCT_NAME}.lnk"
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
SectionEnd
构建命令总结
# 1. Maven构建 mvn clean package # 2. 生成安装包目录结构 cd target mkdir -p myapp-1.0.0/bin mkdir -p myapp-1.0.0/lib mkdir -p myapp-1.0.0/config # 3. 复制文件 cp myapp.jar lib/ cp -r lib/ myapp-1.0.0/lib/ cp bin/run.sh bin/run.bat myapp-1.0.0/bin/ cp config/* myapp-1.0.0/config/ # 4. 打包 tar -czf myapp-1.0.0-linux.tar.gz myapp-1.0.0/ zip -r myapp-1.0.0-windows.zip myapp-1.0.0/
这个案例覆盖了Java应用打包的主要方式,您可以根据需求选择适合的方案,对于简单应用,建议使用Maven + 启动脚本;对于企业级应用,推荐使用install4j或jpackage。