user842225 user842225 - 2 months ago 29
Groovy Question

read & write properties file in gradle build script

I am new in Gradle build script. Say, I have two properties files in my file system. I would like to read all fields in the two properties files & write to a new properties file. How to achieve this in gradle?

For example, file1.properties contains:

name = John
age = 30


file2.properties contains:

gender = male


I would like my build script read all the fields in two files & write to a new file in a different location. That's new file contains:

name = John
age = 30
gender = male


How to do it in gradle?

Answer

You can try this simple script in groovy:

def targetFile = new File("<combinedFileWithPath>")

// Create directory structure of the target file before writing the file
targetFile.parentFile.mkdirs()

// Create target file using writer
targetFile.withWriter { w ->

    // List of input files
    ["<firstFilePath>", "<secondFilePath", "<thirdFilePath>"].each { f ->

        // Use reader on current file
        new File(f).withReader { r ->

            // Append data from each file to the writer of the combined file
            w << r << "\n"
        }
    }
}
Comments