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

问题描述 投票:0回答:5

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

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

task concatenate << {
   // concatenate the files to file.js
}

我正在使用 Gradle 2.3。

gradle
5个回答
9
投票

左移/“<<" is deprecated in gradle 3.4 You may use something like:

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 }
    }

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' }
        }
    }
}

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

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

在 groovy 中连接文件


5
投票

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

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

3
投票
(new File('test.js')).text = file('test1.js').getText() + file('test2.js').getText()

更新:

供收藏。

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

0
投票

最简单的方法是使用“concat”ant 任务。它具有定义文件集的广泛功能并支持过滤。 请参阅https://ant.apache.org/manual/Tasks/concat.html

Kotlin 变体:

register("mergeFiles") {
    doLast {
        ant.withGroovyBuilder {
            "concat"("destfile" to file("path/to/resulting/file.txt")) {
                "fileset"("file" to file("path/to/file1.txt"))
                "fileset"("file" to file("path/to/file2.txt"))
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.