我确定这是微不足道的,但我找不到解决方法...
在我的build.gradle
中,我希望processResources
任务创建(而不是复制或填充某些模板)要由Java程序加载的资源文件。
我实现了以下目标:
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")
}
}
您可以在println
上方看到完全打印我所需的内容。但是,如何将这个字符串写入文件而不是控制台?
答案 0 :(得分:1)
您可以使用以下代码
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")
}
答案 1 :(得分:1)
一种实现方法是定义一个自定义任务,该任务将从 extra 配置生成此“索引”文件,并使现有的processResources
任务依赖于此自定义任务
类似的方法会起作用:
// 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