Gradle task replace string in .java file

本小妞迷上赌 提交于 2019-12-18 04:36:28

问题


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 to copy it I had to save it somewhere - thats why I went for solution: copy to temp location while replacing lines > delete original file > copy duplicated file back to original place > delete temp file. Is there better solution?


回答1:


May be you should try something like ant's replaceregexp:

task myCopy << {
    ant.replaceregexp(match:'aaa', replace:'bbb', flags:'g', byline:true) {
        fileset(dir: 'src/main/java/android/app/cfg', includes: 'TestingConfigCopy.java')
    }
}

This task will replace all occurances of aaa with bbb. Anyway, it's just an example, you can modify it under your purposes or try some similar solution with ant.




回答2:


To complement lance-java's answer, I found this idiom more simple if there's only one value you are looking to change:

task generateSources(type: Copy) {
    from 'src/replaceme/java'
    into "$buildDir/generated-src"
    filter { line -> line.replaceAll('xxx', 'aaa') }
}



回答3:


  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


来源:https://stackoverflow.com/questions/33464577/gradle-task-replace-string-in-java-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!