将属性从外部文件加载到build.gradle

时间:2013-12-20 14:46:17

标签: groovy gradle build.gradle android-gradle

我有这个:

def loadProperties(String sourceFileName) {
    def config = new Properties()
    def propFile = new File(sourceFileName)
    if (propFile.canRead()) {
        config.load(new FileInputStream(propFile))
        for (Map.Entry property in config) {
            ext[property.key] = property.value;
        }
    }
}

loadProperties 'gradle.properties'

如何引用build.gradle中的属性(ndk.dir)?

def ndkBuild = new File("$ndk.dir", 'ndk-build')

有没有更好的方法从文件gradle.properties读取ndk.dir? 我该如何使用它?

def ndkBuild = new File("$ndk.dir", 'ndk-build')

完整代码:

task buildNative(type: Exec) {
    loadProperties 'gradle.properties'
    if (System.getenv('NDK_HOME') != null || "$ndk.dir" != null) {
        if ("$ndk.dir" != null) {
            def ndkBuild = new File("$ndk.dir", 'ndk-build')
        } else {
            def ndkBuild = new File(System.getenv('NDK_HOME'), 'ndk-build')
        }
        workingDir "jni"
        executable ndkBuild
    } else {
        throw new GradleException('Reason: NDK_HOME not set or ndk.dir is missing in gradle.properties...')
    }
}

def loadProperties(String sourceFileName) {
    def config = new Properties()
    def propFile = new File(sourceFileName)
    if (propFile.canRead()) {
        config.load(new FileInputStream(propFile))
        for (Map.Entry property in config) {
            ext[property.key] = property.value;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

就像ndk.dir一样,"$ndk.dir"首先获取ndk属性,然后获取dir属性,这不是您想要的。 (这在错误消息中也很明显,其中显示“无法找到属性'ndk'”。)相反,这应该有效:

def ndkBuild = new File(project.property('ndk.dir'), 'ndk-build')

更安全的解决方案是将整个Properties对象存储为一个额外的属性:

...
ext.externalProps = config

然后您可以访问外部属性,如下所示:

def ndkBuild = new File(externalProps['ndk.dir'], 'ndk-build')