Concatenating multiple files into one using gradle

Hi,

Forgive me in case the terminology is not correct as I am new to gradle and migrating one ant based build to gradle!

I want to concatenate multiple files into one using gradle, I know that I can call ant and do that but I want to utilize gradle powerful copy task to achieve this. To do this I was thinking to extend Copy task itself but I didn’t get any solid article in google explaining how to extend any core task.

My new task will have another property which will define target/concatenated file name where as source file names can still be fetched using existing ‘from’ clousures!

Thanks, Anshuman

I’d just write my own custom task in Groovy that knows how to concatinate files. You can either put this code into your build script, use the ‘buildSrc’ project or write a plugin if you want to share the code among projects. Here’s an example:

class ConcatFiles extends DefaultTask {
    @InputFiles
    FileCollection files
          @OutputFile
    File target
          @TaskAction
    void concat() {
        target.withWriter { writer ->
            files.each { file ->
                file.withReader { reader ->
                    writer << reader << '\n'
                }
            }
        }
    }
}

To use this task in your build, you can write an enhance task and assign the desired input and output files:

task concat(type: ConcatFiles) {
    files = files('test1.txt', 'test2.txt', 'test3.txt')
    target = file("$buildDir/concat.txt")
}
2 Likes

Yes, this is one of the approach to do this, but as I mentioned I was thinking if I can utilize ‘from’, ‘include’ & ‘exclude’ also, something like -

task concat(type: ConcatFiles) {
  from(sourceSets.main.java.srcDirs) {
    include 'file-1.properties'
    include 'file-2.properties'
    include 'file-3.properties'
    concatTo "$buildDir/concat.txt"
  }
}

This will give me luxury to add regular expressions as well as inclusions and exclusions same as it works for Copy task.

There is another reason as to why I want this type of approach because I want to perform multiple concatenation under one task!

Thanks, Anshuman

1 Like