在Gralde中我们可以很方便的替换Manifest中的字符串:
manifestPlaceholders = [UMENG_CHANNEL_VALUE: "myapp"]
但是,这种方式不适用于其他文件。
举个栗子,首先要有个测试文件,Test.java:
public class Test {
public static final String Str = "${TEST_KEY}";
}
然后build.gradle中添加函数和task:
def static replaceText(File file, String key, String value) {
def fileText = file.text
def regex = '\\$\\{' + key + '\\}'
fileText = (fileText =~ /${regex}/).replaceAll(value)
file.write(fileText)
}
task doSth {
doLast {
File file = new File("${projectDir}/Test.java")
replaceText(file, 'TEST_KEY', 'this is test value')
}
}
执行task doSth:
$ ./gradlew -q doSth
最后Test.java的${TEST_KEY}
就被替换了:
public class Test {
public static final String Str = "this is test value";
}