首页 > 解决方案 > 以编程方式在 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打印出我需要的内容。但是如何将此字符串写入文件而不是控制台?

标签: gradle

解决方案


您可以使用以下代码

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

推荐阅读