【问题标题】:How to copy files into flat directory in Gradle如何将文件复制到 Gradle 中的平面目录中
【发布时间】:2021-05-11 10:19:47
【问题描述】:

我正在尝试编写一个 Gradle 任务来将特定文件从深层树复制到平面文件夹中。

第一次尝试:

task exportProperties << {
  copy {
    from "."
    into "c:/temp/properties"
    include "**/src/main/resources/i18n/*.properties"
  }
}

这会复制正确的文件,但不会使结构变平,所以我最终得到了原始项目中的每个文件夹,其中大部分都是空的。

第二次尝试,根据我看到的答案herehere

task exportProperties << {
  copy {
    from fileTree(".").files
    into "c:/temp/properties"
    include "**/src/main/resources/i18n/*.properties"
  }
}

这一次,它没有复制任何东西。

第三次尝试:

task exportProperties << {
  copy {
    from fileTree(".").files
    into "c:/temp/properties"
    include "*.properties"
  }
}

几乎可以工作,除了当我只想要特定路径中的文件时它会复制每个 *.properties 文件。

【问题讨论】:

    标签: gradle


    【解决方案1】:

    我以类似的方式解决了这个问题:

    task exportProperties << {
      copy {
        into "c:/temp/properties"
        include "**/src/main/resources/i18n/*.properties"
    
        // Flatten the hierarchy by setting the path
        // of all files to their respective basename
        eachFile {
          path = name
        }
    
        // Flattening the hierarchy leaves empty directories,
        // do not copy those
        includeEmptyDirs = false
      }
    }
    

    【讨论】:

    • 这是在 processResources copySpec 的上下文中我可以让它工作的唯一方法。
    【解决方案2】:

    我让它像这样工作:

    task exportProperties << {
      copy {
        from fileTree(".").include("**/src/main/resources/i18n/*.properties").files
        into "c:/temp/properties"
      }
    }
    

    【讨论】:

    • 我喜欢这个答案的正确性
    • 你能帮忙解释一下这个from语句的语法吗?方法 fileTree() 返回一个 ConfigurableFileTree,这个 ConfigurableFileTree 具有返回 PatternFilterable 的 include 方法。我只能在 PatternFilterable 中找到 getFiles() 方法。 “文件”从哪里来?是不是因为 Groovy 的语法/语法糖?
    • @linc01n 抱歉,我回答这个问题几个月后就没有使用过 Gradle。我的猜测是和你说的一样,myObject.xyz相当于myObject.getXyz()
    • 这正是它在 Groovy @Kip 中的工作原理
    【解决方案3】:

    您可以通过将闭包输入Copy.eachFile 方法(包括目标文件路径)来即时修改复制文件的多个方面:

    copy {
        from 'source_dir'
        into 'dest_dir'
        eachFile { details ->
            details.setRelativePath new RelativePath(true, details.name)
        }
    }
    

    这会将所有文件直接复制到指定的目标目录中,但它也会复制原始目录结构而没有文件。

    【讨论】:

    • 使用includeEmptyDirs = false 省略空文件夹
    【解决方案4】:

    我能够以与 Kip 类似的方式解决这个问题,但倒过来了:

    distributions {
        main {
            // other distribution configurations here...
            contents {
                into('config') {
                    exclude(['server.crt', 'spotbugs-exclusion-filters.xml'])
                    from fileTree('src/main/resources').files
                }
            }
        }
    }
    

    以这种方式配置 CopySpec 时,空目录没有问题。

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多