如何在Gradle中连接多个文件?

Mar*_*rga 7 gradle

有没有一种简单的方法可以在Gradle中将多个文本文件连接成一个文件?构建脚本应如下所示:

FileCollection jsDeps = files(
   'file1.js',
   'file2.js'
   // other files here
)

task concatenate << {
   // concatenate the files to file.js
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Gradle 2.3.

Aar*_*jav 6

您还可以将文件注册为输入/输出以帮助增量构建。它对于较大的文件特别有用。

像这样的东西:

task 'concatenateFiles', {
    inputs.files( fileTree( "path/to/dir/with/files" ) ).skipWhenEmpty()
    outputs.file( "$project.buildDir/tmp/concatinated.js" )
    doLast {
        outputs.files.singleFile.withOutputStream { out ->
            for ( file in inputs.files ) file.withInputStream { out << it << '\n' }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除了 fileTree 之外,它还可以替换为源集/源集输出、特定文件、来自不同任务的输出等。

关于任务输入/输出的 Gradle 文档

在groovy中连接文件


Opa*_*pal 5

以下任务应该完成这项工作:

task concatenate << {
    def toConcatenate = files('f1', 'f2', 'f3')
    def output = new File('output')
    toConcatenate.each { f -> output << f.text }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ust 5

在gradle 3.4中不建议使用leftShift /“ <<”。

task concatenate {
    doLast {
        def toConcatenate = files("filename1", "filename2", ...)
        def outputFileName = "output.txt"
        def output = new File(outputFileName)
        output.write('') // truncate output if needed
        toConcatenate.each { f -> output << f.text }
    }
Run Code Online (Sandbox Code Playgroud)


Cyb*_*eks 3

(new File('test.js')).text = file('test1.js').getText() + file('test2.js').getText()
Run Code Online (Sandbox Code Playgroud)

更新:

用于收藏。

(new File('test.js')).text = files('test1.js', 'test2.js').collect{it.getText()}.join("\n")
Run Code Online (Sandbox Code Playgroud)