我想使用gradle从我的代码创建.jar,然后从.jar创建.exe。我有一个简单的Java代码
package project;
public class main {
public static void main(String[] args) {
System.out.println("hello");
}
}
和一个 build.gradle 文件。
plugins {
id 'java'
id 'idea'
id 'com.github.johnrengelman.shadow'
id 'edu.sc.seis.launch4j'
}
jar.enabled = false
group 'project'
version '1.0-SNAPSHOT'
java {
sourceCompatibility = 1.8
}
repositories {
}
dependencies {
}
shadowJar {
archiveBaseName.set('toJarToExeFat')
archiveVersion.set('0.1')
archiveClassifier.set('')
manifest {
attributes 'Main-Class': 'project.main'
}
}
tasks.shadowJar.dependsOn tasks.build
createExe {
outfile = 'test.exe'
mainClassName = 'project.main'
jar = "C:/work/java/toJarToExe/build/libs/toJarToExeFat-0.1.jar"
}
tasks.createExe.dependsOn tasks.shadowJar
它可以工作,但是当我运行 .exe 时,我得到“此应用程序需要 Java 运行时环境 1.8.0”。
我期待收到.exe,就像我用 C 编写这个程序一样
您获得了一个可执行文件。只是使用 launch4j 可执行文件仍然需要 Java 运行时才能执行。 Launch4j 仅创建一个启动器来简化从 Windows 命令行执行应用程序。阅读 launch4j 文档以了解其工作原理。请注意,Gradle 仅将 launch4j 作为构建的一部分执行。创建可执行文件不是 Gradle 功能。
早上好,要解决此问题并创建不需要外部 JRE 的独立可执行文件,您需要确保生成的 .exe 文件正确引用嵌入式 JRE。您可以通过修改 Gradle 构建脚本和 Launch4j 配置来完成此操作。
这是 build.gradle 脚本的更新版本,进行了必要的更改:
plugins {
id 'java'
id 'com.github.johnrengelman.shadow'
id 'edu.sc.seis.launch4j' version '2.4.6' // Make sure you're using a compatible version of Launch4j
}
jar.enabled = false
group 'project'
version '1.0-SNAPSHOT'
java {
sourceCompatibility = 1.8
}
repositories {
// You might need to add a repository for the embedded JRE if it's not available locally.
// mavenCentral()
}
dependencies {
// Define the embedded JRE dependency
implementation 'com.zeroturnaround:zt-exec:1.11' // Or a suitable alternative
}
shadowJar {
archiveBaseName.set('toJarToExeFat')
archiveVersion.set('0.1')
archiveClassifier.set('')
manifest {
attributes 'Main-Class': 'project.main'
}
}
tasks.shadowJar.dependsOn tasks.build
createExe {
mainClassName = 'project.main'
jrePath = 'path/to/your/embedded/jre' // Set this to the path where your JRE is located
// Specify additional JVM options if needed
// jvmOptions = ['-Dsome.property=value']
// Include JRE files in the generated .exe
includeJre = true
outfile = 'test.exe'
jar = tasks.shadowJar.archiveFile.get().asFile
// Set the icon and other options if needed
// icon = 'path/to/your/icon.ico'
// bundledJre64 = true
}
tasks.createExe.dependsOn tasks.shadowJar