Gradle 清理并复制 JAR 文件

Gradle clean and copy JAR file

我正在使用 Gradle 构建一个 java 应用程序,我想将最终的 jar 文件传输到另一个文件夹中。我想在每个 build 上复制文件并在每个 clean.

上删除文件

不幸的是,我只能完成其中一项任务,而不能同时完成两项任务。当我激活任务 copyJar 时,它成功复制了 JAR。当我包含 clean 任务时,不会复制 JAR,如果那里有文件,它会被删除。就好像有一些任务调用clean

有什么解决办法吗?

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()    
    }

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

这样每次评估都会删除文件,这不是你想要的。将其更改为:

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

这会配置清理任务并添加要在执行时删除的 JAR。

@nickb 关于 clean 任务是正确的,但您还需要修复 copyJar 任务。 copy { ... } 方法在配置阶段被调用,所以每次 gradle 都会被调用。简单去掉方法,使用Copy任务类型的配置方法:

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

同样的问题适用于 allprojects 闭包中的 clean 任务。只需将 file('out').deleteDir() 替换为 delete 'out'。在 documentation.

中查看有关 配置阶段 执行阶段 之间差异的更多信息