JavaExec - How to execute a main class from the command line with Gradle

1 - Steps

1.1 - The build file

The below build file define a JavaExec task with the name myCli and set:

  • the main class
  • the class path
  • the current directory
  • the arguments

val cd: String by project
val arguments: String by project

tasks.register<JavaExec>("myCli") {
  main = "com.example.cli"
  classpath = sourceSets["main"].runtimeClasspath
    workingDir = File(cd)
  if (project.hasProperty("arguments")){
     * We split and escape the arguments to not have any file wildcard expansion
     * (ie star will not become a list of files)
    args = arguments.split(" ").map{s->"\""+s+"\""}

1.2 - The dos script

The dos script that calls the task myCli. This file should located at the root of the gradle project (otherwise you need to change the --project-dir option.

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal


REM This script call the myCli task defined in the gradle.kts build
REM The properties are passed via argument

@if ".%*" == "." (
	@gradle myCli --project-dir %SCRIPT_PATH% -PcurrentDirectory=%cd%
) ELSE (
	@gradle myCli --project-dir %SCRIPT_PATH% -PcurrentDirectory=%cd% -Parguments="%*"

if "%OS%"=="Windows_NT" endlocal

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap