gradle - copy file after its generation

Just made few corrections to above Answers:

jar {
    baseName = "$artifactId"
    version =  '0.0.1'
}

task copyJar(type: Copy) {
    from jar // copies output of file produced from jar task
    into 'destination-folder'
}

build.finalizedBy copyJar

I think the above answer is somehow old. Here is an answer using gradle 3.3

jar {
    baseName = 'my-app-name'
    version =  '0.0.1'
}

task copyJar(type: Copy) {
    from jar // here it automatically reads jar file produced from jar task
    into 'destination-folder'
}

build.dependsOn copyJar

The culprit is your copyJarToBin task. when doing

task copyJarToBin {
    copy {
        from 'build/libs/GradleJarProject.jar'
        into "d:/tmp"
    }
}

you copy the jar during the configuration time by using the copy method. (see the gradle user guide at https://docs.gradle.org/current/userguide/userguide_single.html#sec:build_phases to understand the build lifecycle) You want to run the actual copy operation during the execution phase (the execution of the task).

One way to solve that is to move the call of the copy method into a doLast block:

task copyJarToBin {
    doLast {
        copy {
            from 'build/libs/GradleJarProject.jar'
            into "d:/tmp"
        }

    }
}

The problem with this approach is that you won't benefit of gradles incremental build feature and copy that file every single time you execute the task even though the file hasn't changed.

A better and more idiomatic way of writing your copyJarToBin task is to change your task implementation to use the Copy task type:

task copyJarToBin(type: Copy) {
    from 'build/libs/GradleJarProject.jar'
    into "d:/tmp"
}   

We can even improve this snippet by taking advantage of gradle's autowiring feature. You can declare the output of one task as input to another. So instead of writing `build/libs/GradleJarProject.jar' you can simply do:

task copyJarToBin(type: Copy) {
    from createJar // shortcut for createJar.outputs.files
    into "d:/tmp"
}   

Now you don't need to bother about task ordering as gradle know that the createJar task must be executed before the copyJarToBin task can be executed.

Tags:

Java

Gradle