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

Groovy 将属性从外部文件加载到build.gradle中,groovy,gradle,build.gradle,android-gradle-plugin,Groovy,Gradle,Build.gradle,Android Gradle Plugin,我有这个: 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

我有这个:

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;
        }
    }
}

就像
ndk.dir
“$ndk.dir”
首先获取
ndk
属性,然后获取
dir
属性,这不是您想要的。(这在错误消息中也很明显,其中显示“找不到属性‘ndk’”)。相反,这应该可以工作:

def ndkBuild = new File(project.property('ndk.dir'), 'ndk-build')
更安全的解决方案是将整个
属性
对象存储为单个额外属性:

...
ext.externalProps = config
然后,您可以访问如下外部属性:

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

请始终准确描述问题是什么,您收到的错误消息是什么,等等。问题是“$ndk.dir”不起作用,我想我用错了?这不是一个准确的描述。您得到的确切错误消息是什么?等等。*出了什么问题:评估项目时出现问题:primavista android已重新加载。“>在任务上找不到属性“ndk”:primavista android已重新加载:buildNative。已更新问题,并提供完整示例。