是否有一种简单的方法可以在 Gradle 中将多个文本文件连接成一个文件?构建脚本应该如下所示:
FileCollection jsDeps = files(
'file1.js',
'file2.js'
// other files here
)
task concatenate << {
// concatenate the files to file.js
}
我正在使用 Gradle 2.3。
左移/“<<" 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 }
}
您还可以将文件注册为输入/输出以帮助增量构建。这对于较大的文件特别有帮助。
类似这样的:
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,它还可以替换为源集/源集输出、特定文件、来自不同任务的输出等。
以下任务应该可以完成这项工作:
task concatenate << {
def toConcatenate = files('f1', 'f2', 'f3')
def output = new File('output')
toConcatenate.each { f -> output << f.text }
}
(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")
最简单的方法是使用“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"))
}
}
}
}