Gradle task replace string in .java file

前端 未结 3 1193
醉话见心
醉话见心 2020-12-03 10:31

I want to replace few lines in my Config.java file before the code gets compiled. All I was able to find is to parse file through filter during copying it. As soon as I have

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 10:53

    1. I definitely wouldn't overwrite the original file
    2. I like to keep things directory based rather than filename based so if it were me, I'd put Config.java in it's own folder (eg src/replaceme/java)
    3. I'd create a generated-src directory under $buildDir so it's deleted via the clean task.

    You can use the Copy task and ReplaceTokens filter. Eg:

    apply plugin: 'java'
    task generateSources(type: Copy) {
        from 'src/replaceme/java'
        into "$buildDir/generated-src"
        filter(ReplaceTokens, tokens: [
            'xxx': 'aaa', 
            'yyy': 'bbb'
        ])
    }
    // the following lines are important to wire the task in with the compileJava task
    compileJava.source "$buildDir/generated-src"
    compileJava.dependsOn generateSources
    

提交回复
热议问题