Gradle task replace string in .java file

I want to replace some lines in the Config.java file before the code is compiled. All I could find was to parse the file through a filter while it was being copied. As soon as I needed to copy it, I had to save it somewhere - that’s why I decided: copy to a temporary place when replacing lines> delete the source file> copy the duplicated file back to the original place> delete the temporary file. Is there a better solution?

+6
source share
3 answers

Maybe you should try something like ant 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 aaa events with bbb . In any case, this is just an example, you can change it for your own purposes or try some similar solution using ant.

+8
source
  • I would definitely not overwrite the original file
  • I like to store files based on files, not on the file name, so if it were me, I would put Config.java in its own folder (e.g. src/replaceme/java )
  • I created the generated-src directory in $buildDir to remove it using the clean task.

You can use the Copy and Replace Filter program. For instance:

 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 
+3
source

To complement lance-java answer, I found this idiom simpler if there is only one value that you want to change:

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

All Articles