Gradle字符串替换

在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";
}
    原文作者:goodl
    原文地址: https://www.jianshu.com/p/9bbbf66b4fbf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞