Search code examples
androidkotlingradlejargradle-kotlin-dsl

Execute Jar file with arguments using Gradle task in Kotlin DSL


I want to run an external Jar file with arguments that I have saved in my project. The function doesn't seem to work. I am not sure if the syntax is correct.

tasks.register("myGradleTask", Exec::class) {
  val folder = "${rootProject.rootDir}/myFolder/"
  val jarFilePath = "${rootProject.rootDir}/Scripts/MyExternalJarFile.jar"
  executable(jarFilePath)
  commandLine(arrayOf("java", "-jar", "-app AppName -i $folder -o $folder"))
}

Solution

  • I'd suggest using the JavaExec class which is specifically designed for executing JVM programs (assuming you have the java plugin applied).

    One mistake you look to be making is passing the Kotlin KClass to the register method rather than the Java Class.

    Try this:

    tasks.register("myGradleJavaExec", JavaExec::class.java) {
        val folder = "${rootProject.rootDir}/myFolder/"
        val jarFilePath = "${rootProject.rootDir}/Scripts/MyExternalJarFile.jar"
        classpath = files(jarFilePath)
        args("-app", "AppName", "-i", folder, "-o", folder) // Specify args separately
    }