Skip to content

Instantly share code, notes, and snippets.

@rafayali
Last active February 6, 2021 19:06
Show Gist options
  • Save rafayali/73f43adfe3e6511ace8863a64058f361 to your computer and use it in GitHub Desktop.
Save rafayali/73f43adfe3e6511ace8863a64058f361 to your computer and use it in GitHub Desktop.
A gradle function to read properties from a file
def getProperty(String filename, String propName) {
def propsFile = rootProject.file(filename)
if (propsFile.exists()) {
def props = new Properties()
props.load(new FileInputStream(propsFile))
if (props[propName] != null) {
return props[propName]
} else {
print("No such property " + propName + " in file " + filename)
}
} else {
print(filename + " does not exist!")
}
}
@rafayali
Copy link
Author

rafayali commented Feb 6, 2021

Sample usage inside an android's app module gradle file

android {
    defaultConfig {
        .....
        buildConfigField "String", "NEWS_API_KEY", "\"${getProperty("local.properties", "news_api_key")}\""
        .....
    }
}

def getProperty(String filename, String propName) {
    def propsFile = rootProject.file(filename)
    if (propsFile.exists()) {
        def props = new Properties()
        props.load(new FileInputStream(propsFile))
        if (props[propName] != null) {
            return props[propName]
        } else {
            print("No such property " + propName + " in file " + filename)
        }
    } else {
        print(filename + " does not exist!")
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment