Gradle 任务替换 .java 文件中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33464577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gradle task replace string in .java file
提问by Srneczek
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?
我想在编译代码之前替换我的 Config.java 文件中的几行。我能找到的只是在复制文件时通过过滤器解析文件。一旦我必须复制它,我就必须将它保存在某个地方 - 这就是我寻求解决方案的原因:复制到临时位置,同时替换行> 删除原始文件 > 将复制的文件复制回原始位置 > 删除临时文件。有更好的解决方案吗?
采纳答案by Stanislav
May be you should try something like ant's replaceregexp:
可能你应该尝试像 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.
此任务将替换所有出现的aaa
with bbb
。无论如何,这只是一个示例,您可以根据自己的目的对其进行修改或尝试使用 ant 进行一些类似的解决方案。
回答by Vic Seedoubleyew
To complement lance-java
's answer, I found this idiom more simple if there's only one value you are looking to change:
为了补充lance-java
的答案,如果您只想更改一个值,我发现这个习语更简单:
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.
警告:请记住,该Copy
任务仅在源文件更改时才会运行。如果您希望根据其他条件进行替换,则需要使用 Gradle 的增量构建功能来指定。
回答by lance-java
- I definitely wouldn't overwrite the original file
- 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
) - I'd create a
generated-src
directory under$buildDir
so it's deleted via theclean
task.
- 我绝对不会覆盖原始文件
- 我喜欢保持基于目录而不是基于文件名的东西,所以如果是我,我会将 Config.java 放在它自己的文件夹中(例如
src/replaceme/java
) - 我会在下面创建一个
generated-src
目录,$buildDir
以便通过clean
任务删除它。
You can use the Copy task and ReplaceTokens filter. Eg:
您可以使用 Copy 任务和 ReplaceTokens 过滤器。例如:
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