1. 程式人生 > >jar包打包成exe示例

jar包打包成exe示例

cnblogs resource gpo out itl direct cat AR rect

jar包打包成exe示例

說明

針對基於maven的Java項目,通常會打包成jar,
如果要把jar文件包裝成exe文件,僅需要在pom.xml配置文件中增加一個插件即可

這裏我們用launch4j

環境

  • jdk1.8
  • maven 3.5.2

Main方法

邏輯很簡單,就是如果命令行有參數,則打印命令行的第一個參數,
無參數則打印“Hell World!”。

package com.hui;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        if (null
!= args && args.length > 0) { System.out.println(args[0]); } else { System.out.println("Hello World!"); } } }

pom.xml 示例

僅需要在build環節加入以下插件

<build>
        <plugins>
            <plugin>
                <groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId> <executions> <execution> <id>l4j-clui</id> <phase>package</phase> <goals><goal>
launch4j</goal></goals> <configuration> <headerType>console</headerType> <outfile>target/encc.exe</outfile> <jar>target/java2exe-1.0-SNAPSHOT.jar</jar> <errTitle>encc</errTitle> <classPath> <mainClass>com.hui.App</mainClass> <addDependencies>false</addDependencies> <preCp>anything</preCp> </classPath> <jre> <minVersion>1.5.0</minVersion> </jre> <versionInfo> <fileVersion>1.2.3.4</fileVersion> <txtFileVersion>txt file version?</txtFileVersion> <fileDescription>a description</fileDescription> <copyright>my copyright</copyright> <productVersion>4.3.2.1</productVersion> <txtProductVersion>txt product version</txtProductVersion> <productName>E-N-C-C</productName> <internalName>ccne</internalName> <originalFilename>original.exe</originalFilename> </versionInfo> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>assembly</id> <phase>package</phase> <goals><goal>single</goal></goals> <configuration> <descriptors> <descriptor>assembly.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin> </plugins> </build>

同時在項目根目錄新建一個assembly.xml文件

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>cdc-upgrade</id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>*.exe</include>
            </includes>
        </fileSet>
    </fileSets>
</assembly>

打包

執行

mvn clean package 

打包以後,可以看到項目target目錄下生成了 encc.exe這個文件

在encc.exe所在的目錄下執行

encc aaa

輸出結果

aaa

技術分享圖片

完整源碼

代碼

參考文檔

Maven Launch4j Plugin

jar包打包成exe示例