How to read a properties files and use the values in project Gradle script?

前端 未结 3 1927
悲哀的现实
悲哀的现实 2020-12-04 14:08

I am working on a Gradle script where I need to read the local.properties file and use the values in the properties file in build.gradle. I am doin

3条回答
  •  情书的邮戳
    2020-12-04 15:01

    If using the default gradle.properties file, you can access the properties directly from within your build.gradle file:

    gradle.properties:

    applicationName=Admin
    projectName=Hello Cool
    

    build.gradle:

    task printProps {
        doFirst {
            println applicationName
            println projectName
        }
    }
    

    If you need to access a custom file, or access properties which include . in them (as it appears you need to do), you can do the following in your build.gradle file:

    def props = new Properties()
    file("build.properties").withInputStream { props.load(it) }
    
    task printProps {
        doFirst {
            println props.getProperty("application.name")
            println props.getProperty("project.name")
        }
    }
    

    Take a look at this section of the Gradle documentation for more information.

    Edit

    If you'd like to dynamically set up some of these properties (as mentioned in a comment below), you can create a properties.gradle file (the name isn't important) and require it in your build.gradle script.

    properties.gradle:

    ext {
        subPath = "some/sub/directory"
        fullPath = "$projectDir/$subPath"
    }
    

    build.gradle

    apply from: 'properties.gradle'
    
    // prints the full expanded path
    println fullPath
    

提交回复
热议问题