Gradle task replace string in .java file

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.


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

Caveat: Keep in mind that the Copy task will only run if the source files change. If you want your replacement to happen based on other conditions, you need to use Gradle's incremental build features to specify that.

Tags:

Java

Task

Gradle