在 Gradle 构建中替换文件

Iro*_*che 4 java groovy build gradle

我正在尝试用 Gradle 构建脚本生成的新文件替换我的资源文件夹 (src/main/resources) 中的文件。我在做这件事时遇到了麻烦;排除似乎被记住了,并阻止了我的新文件的添加。

这是一个说明行为的简短示例。

项目结构:

TestProject
-- src/main/java
---- entry
------ EntryPoint.java
---- run
------ HelloWorldTest.java
-- src/main/resources
---- test.properties // FILE TO REPLACE
Run Code Online (Sandbox Code Playgroud)

src/main/resources 中的 test.properties 内容:

Wrong File with extra text to make it obvious which one is being put into the jar based on size

构建.gradle:

apply plugin: 'java'

task makeProp {
    def propDir = new File(buildDir, "props")
    ext.propFile = new File(propDir, "test.properties")
    outputs.file propFile

    doLast {
        propDir.mkdirs()
        propFile.createNewFile()
        propFile.withWriter('utf-8') { writer ->
            writer.writeLine 'Right File'
        }
    }
}

jar {
    dependsOn('makeProp')

    if (project.hasProperty('testExclude')) {
        sourceSets {
            exclude('test.properties')
        }
    }

    from (makeProp.propFile) {
        into '/'
    }
}
Run Code Online (Sandbox Code Playgroud)

JAR 内容./gradlew build(包括两个文件):

Archive:  TestProject.jar
  Length     Date   Time    Name
 --------    ----   ----    ----
        0  08-07-15 14:27   META-INF/
       25  08-07-15 14:27   META-INF/MANIFEST.MF
        0  08-07-15 13:50   run/
      499  08-07-15 13:50   run/HelloWorldTest.class
        0  08-07-15 13:50   entry/
     1413  08-07-15 13:50   entry/EntryPoint.class
       95  08-07-15 14:27   test.properties
       11  08-07-15 14:03   test.properties
 --------                   -------
     2043                   8 files
Run Code Online (Sandbox Code Playgroud)

JAR 内容./gradlew build -PtestExclude(均不包括文件):

Archive:  TestProject.jar
  Length     Date   Time    Name
 --------    ----   ----    ----
        0  08-07-15 14:29   META-INF/
       25  08-07-15 14:29   META-INF/MANIFEST.MF
        0  08-07-15 13:50   run/
      499  08-07-15 13:50   run/HelloWorldTest.class
        0  08-07-15 13:50   entry/
     1413  08-07-15 13:50   entry/EntryPoint.class
 --------                   -------
     1937                   6 files
Run Code Online (Sandbox Code Playgroud)

Pum*_*use 5

我做了一些非常相似的事情,这对我有用。主要目标是确保任务在创建 jar 和处理文件之前运行。试试这个。

    // create a properties file add it to folder preprocessing
    task propertiesFile << {
        // 
        description 'Dynamically creates a properties file.'

        // needed for the first pass
        def folder = project.file('src/main/resources');
        if(!folder.exists()){
            folder.mkdirs()
        }

        //write it to a propertiess file
        def props = project.file('src/main/resources/test.properties')
        props.delete()
        props << 'write this to my file!!!!'

    }

    processResources.dependsOn propertiesFile
Run Code Online (Sandbox Code Playgroud)