Skip to main content

Gradle : Task to add selected files to jar

Points To Remember

  • You can create local variable in gradle with the type def, e.g def jarName = "ekiras"
  • You can print variable with help of println e.g println "jar name is -> $jarName
  • Gradle task declaration syntax is task taskName(type: taskType){}

Task to add selected files to jar

We will be writing two tasks for this

  1. First task - compileFiles -> this will compile all the files in the project and then save them to the build/classes/ folder of the project
  2. Second Task - makeJar -> this will take all the compile files from the base folder and make a jar of these files in build/lib/ folder of the project.

task compileFiles(type: JavaCompile) {
println '>>>>>>>>>>>>>>>>>>>>> start compiling'
source = sourceSets.main.java.srcDirs
classpath = sourceSets.main.compileClasspath
destinationDir = sourceSets.main.output.classesDir
println '>>>>>>>>>>>>>>>>>>>>> end compiling '
}

task makeJar(type: Jar,dependsOn : 'compileFiles') {
println '>>>>>>>>>>>>>>>>>>>>> start making Jar'
baseName = "ekiras"
def baseFolder = "com/ekiras"
def destFolder = "build/classes/main/com/ekiras"
from("$destFolder/folder1"){into("$baseFolder/folder1")}
from("$destFolder/folder2"){into("$baseFolder/folder2")}
from("$destFolder/folder3"){into("$baseFolder/folder3")}
println '>>>>>>>>>>>>>>>>>>>>> end making Jar'
}

You can run the tasks individually using the following commands.

  • Task 1 - compile all files in project
    gradle compileFiles
  • Task 2 - copy all compiled files from folders(folder1, folder2, folder3) to jar.
    gradle makeJar
    This task will run the task compileFiles before executing this task. baseName in the task defines the name of the jar that will be created. 

So the above task makeJar when run will make a jar by name ekiras.jar in the folder build/lib/

Comments