Malini Kennady
Malini Kennady

Reputation: 373

How to change value in properties file from gradle build

I am new to Gradle. I am using Eclipse Buildship 2.1.1. I want to include the build timestamp in the properties file that I have in source code. I do something like this in build.gradle,

war {
    def propertyFile = file 
    "src/main/java/com/about/About.properties"
    def props = new Properties()
    propertyFile.withReader { props.load(it) }
    println "Before setProperty:"
    println props.getProperty('releaseDate')
    props.setProperty('releaseDate', new Date().format('yyyy-MM-dd-HH:mm:ss'))
 // propertyFile.withWriter { props.store(it) }
    println "After setProperty:"
    println props.getProperty('releaseDate')
    buildDir = new File(rootProject.projectDir, "gradleBuild/" + project.name)
}

This prints the following details correctly,

Before setProperty:
2017-11-22T19:28
After setProperty:
2017-11-24-10:53:57

But this is not reflected in the properties file itself. And if remove comment for propertyFile.withWriter { props.store(it) } it throws error,

No signature of method: java.util.Properties.store() is applicable for argument types: (java.io.BufferedWriter) values: [java.io.BufferedWriter@9a24ce]
  Possible solutions: store(java.io.OutputStream, java.lang.String), store(java.io.Writer, java.lang.String), sort(), sort(java.util.Comparator), sort(groovy.lang.Closure), size()

Is this approach right or should I do this any other way?

Upvotes: 5

Views: 5737

Answers (1)

James Justinic
James Justinic

Reputation: 174

You must write the properties back to the file in order for the file to be updated. The line propertyFile.withWriter { props.store(it) } throws an error because the store method requires 2 arguments. The second argument is a comment added at the top of the file, but it can be null if you don't need it:

propertyFile.withWriter { props.store(it, null) }

Upvotes: 4

Related Questions