Gradle task replace string in .java file

Srneczek picture Srneczek · Nov 1, 2015 · Viewed 22.5k times · Source

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?

Answer

Stanislav picture Stanislav · Nov 1, 2015

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.