Programmatically create a file in Gradle build script

Viewed 7271

I'm sure it is trivial, but I cannot find a way to do it...

In my build.gradle I want processResources task to create (not e.g. copy or fill some tempate) a resource file to be loaded by Java program.

I achieved the following:

processResources {
    ...

    // This is a collection of files I want to copy into resources.
    def extra = configurations.extra.filter { file -> file.isFile () }

    // This actually copies them to 'classes/extra'. It works.
    into ('extra') {
        from extra
    }

    doLast {
        // I want to write this string (list of filenames, one per
        // line) to 'classes/extra/list.txt'.
        println extra.files.collect { file -> file.name }.join ("\n")
    }
}

You can see above a println that prints exactly what I need. But how do I write this string to a file instead of the console?

2 Answers

You can use the following code

task writeToFile {
  // sample list.(you already have it as extra.files.collect { file -> file.name })
  List<String> sample = [ 'line1','line2','line3' ] as String[]  
  // create the folders if it does not exist.(otherwise it will throw exception)
  File extraFolder = new File( "${project.buildDir}/classes/extra")
  if( !extraFolder.exists() ) {
    extraFolder.mkdirs()
  }
  // create the file and write text to it.
  new File("${project.buildDir}/classes/extra/list.txt").text = sample.join ("\n")
}

One way to implement this would be to define a custom task that will generate this "index" file from the extra configuration, and make the existing processResources task depend on this custom task.

Something like that would work:

// Task that creates the index file which lists all extra libs
task createExtraFilesIndex(){
    // destination directory for the index file
    def indexFileDir = "$buildDir/resources/main"
    // index filename
    def indexFileName = "extra-libs.index"
    doLast{
        file(indexFileDir).mkdirs()
        def extraFiles = configurations.extra.filter { file -> file.isFile () }
        // Groovy concise syntax for writing into file; maybe you want to delete this file first.
        file( "$indexFileDir/$indexFileName") << extraFiles.files.collect { file -> file.name }.join ("\n")
    }
}

// make  processResources depends on createExtraFilesIndex task
processResources.dependsOn createExtraFilesIndex
Related