gradle - 以编程方式在 Gradle 构建脚本中创建文件
问题描述
我敢肯定这是微不足道的,但我找不到办法做到这一点......
在我的任务中,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
打印出我需要的内容。但是如何将此字符串写入文件而不是控制台?
解决方案
您可以使用以下代码
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")
}
推荐阅读
- system-verilog - Cadence IUS 模拟器选项
- user-interface - 使用维护模式以外的自定义 ui 卸载产品时出现问题
- r - 如何在 R 的数据集中对不同的变量使用相同的代码?
- python - 在对流层中添加对现有 sns 主题的订阅
- javascript - 如何访问数组中的数组
- ruby - 如何翻译 Rspec 中的默认消息?
- .htaccess - .htaccess 规则可以清理吗?
- html - 行堆叠时更改行中列的高度
- java - 我无法在 android 5.1 上获取通知图像,总是返回 null
- android - 从 Android 应用程序打印到本地以太网连接的打印机(不通过 Internet)