Search code examples
javagradleshadowjar

Gradle clean and copy JAR file


I am building a java application with Gradle and I want to transfer the final jar file in another folder. I want to copy the file on each build and delete the file on each clean.

Unfortunately, I can do only one of the tasks and not both. When I have the task copyJar activated, it successfully copies the JAR. When I include the clean task, the JAR is not copied and if there is a file there it is deleted. It is as if there is some task that calls clean.

Any solutions?

plugins {
    id 'java'
    id 'base'
    id 'com.github.johnrengelman.shadow' version '2.0.2'
}
dependencies {
    compile project(":core")
    compile project("fs-api-reader")
    compile project(":common")
}

task copyJar(type: Copy) {
    copy {
        from "build/libs/${rootProject.name}.jar"
        into "myApp-app"
    }
}

clean {
    file("myApp-app/${rootProject.name}.jar").delete()
}

copyJar.dependsOn(build)

allprojects {
    apply plugin: 'java'
    apply plugin: 'base'

    repositories {
        mavenCentral()
    }

    dependencies {
        testCompile 'junit:junit:4.12'
        compile 'org.slf4j:slf4j-api:1.7.12'
        testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '0.9.26'
    }

    sourceSets {
        test {
            java.srcDir 'src/test/java'
        }
        integration {
            java.srcDir 'src/test/integration/java'
            resources.srcDir 'src/test/resources'
            compileClasspath += main.output + test.output
            runtimeClasspath += main.output + test.output
        }
    }

    configurations {
        integrationCompile.extendsFrom testCompile
        integrationRuntime.extendsFrom testRuntime
    }

    task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') {
        testClassesDirs = sourceSets.integration.output.classesDirs
        classpath = sourceSets.integration.runtimeClasspath
    }
    test {
        reports.html.enabled = true
    }
    clean {
        file('out').deleteDir()    
    }

}

Solution

  • clean {
        file("myApp-app/${rootProject.name}.jar").delete()
    }
    

    This will delete the file on evaluation every time, which is not what you want. Change it to:

    clean {
        delete "myApp-app/${rootProject.name}.jar"
    }
    

    This configures the clean task and adds the JAR to be deleted on execution.