如果我有Java源文件(*.java)或类文件(*.class),如何将其转换为.exe文件?

我还需要一个安装程序。


当前回答

I can be forgiven for being against converting a java program to a .exe Application and I have My reasons. the Major one being that a java program can be compiled to a jar file from A lot of IDE's. When the program is in .jar format, it can run in Multiple Platforms as opposed to .exe which would run Only in very limited Environment. I am for the Idea that Java Programs shoudl not be converted to Exe unless it is very neccesary. One can always write .bat files that runs the Java program while it is a jar file.

如果真的有必要将其转换为exe, Jar2Exe转换器可以默默地完成,也可以附加与主应用程序一起编译的库。

其他回答

从JDK14开始,jpackage取代了@Jay answer中提到的javapackager。Windows版本需要Wix 3.0,使用java应用程序构建一个提供EXE启动器的安装程序是相当简单的。

它还可以与jlink一起使用来构建精简的Java运行时映像,该映像与安装程序捆绑在一起,只包含支持应用程序所需的模块集。如果没有指定运行时,jlink步骤也将由jpackage隐式运行,但我更喜欢单独制作JRE映像,因为它只在更新JDK或向项目添加新的模块依赖项时才会更改。

Java类的main示例:

package exe;
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println("args["+i+"]="+args[i]);
        }
    }
}

下面是在Windows上构建的示例步骤——显然你需要设置你的本地构建环境(Maven / ant / etc)来重新生成:

mkdir jpackage.input\jars tmp
javac -d tmp src\exe\Main.java
pushd tmp && jar cvf ..\jpackage.input\jars\myapp.jar . && popd

检查它的运行情况:

java -cp jpackage.input\jars\myapp.jar exe.Main X Y Z

使用jlink为应用程序使用的模块集创建一个运行时映像:

set jlink.modules=java.base
jlink --add-modules %jlink.modules% --strip-debug --no-man-pages --no-header-files --compress=1 --output jpackage.jre

如果上面有缺失的模块,你应该检查jlink JRE运行时映像可以运行你的应用程序:

jpackage.jre\bin\java -cp jpackage.input\jars\myapp.jar exe.Main X Y Z

使用jpackage生成安装程序,基于日期+小时的应用程序版本(这节省了每次重新安装时卸载的需要),并打印出所有系统属性-测试后删除参数“- xshowsettings:properties”:

set appver=%date:~6,2%.%date:~3,2%.%date:~0,2%%time:~0,2%
jpackage --win-console --input jpackage.input --runtime-image jpackage.jre --app-version %appver% --type exe --name "MyApp" --dest jpackage.dest --java-options "-XshowSettings:properties" --main-jar jars\myapp.jar --main-class exe.Main

运行安装程序:

jpackage.dest\MyApp-%appver%.exe

测试应用程序:

"C:\Program Files\MyApp\MyApp.exe" ONE 2 THREE

... Prints system properties ...

args[0]=ONE
args[1]=2
args[2]=THREE

你可以用Janel。最后一个是作为应用程序启动器或服务启动器(可从4.x获得)。

或者,您可以使用一些java-to-c转换器(例如JCGO),并将生成的C文件编译为目标平台的本机二进制(.exe)文件。

以我之见,JSmooth似乎做得相当不错。

Launch4j

Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executables. The executable can be configured to search for a certain JRE version or use a bundled one, and it's possible to set runtime options, like the initial/max heap size. The wrapper also provides better user experience through an application icon, a native pre-JRE splash screen, a custom process name, and a Java download page in case the appropriate JRE cannot be found. – Launch4j's website