为什么空集合上的每个闭包至少运行一次?

Fyl*_*lke 7 groovy

我有一个从Web服务器下载文件的功能,有时会提供空集合.在函数中,我在该集合上调用每个函数,我期望发生的是函数只是退出,每个闭包都没有运行.问题是它确实运行了一个空filename参数,并且当FileOutputStream被提供给目录而不是文件时,它的创建就会变得繁荣.

def get(String baseUrl, List files, String targetDir) {
    files.each { filename ->
    // Goes BOOM on next line
    def fos = new FileOutputStream(targetDir + File.separator + filename)
    ...
}
Run Code Online (Sandbox Code Playgroud)

为什么Groovy表现得像这样,我应该怎么做呢?

tim*_*tes 11

它不,所以我假设files包含一些东西(比如null?)

[].each {
  println "boom"  // This doesn't appear
}

[null].each {
  println "pow!"  // this does
}
Run Code Online (Sandbox Code Playgroud)

假设它null在您的文件列表中导致问题,您可以通过以下方式摆脱它们:

files.findAll().each { filename ->
  def fos = new FileOutputStream( new File( targetDir, filename ) )
  ...
Run Code Online (Sandbox Code Playgroud)

或者当然,首先使生成List的东西不添加空值

编辑

实际上,听起来你有一个带有空字符串的List ......

findAll修复程序应仍能正常工作,为空字符串赋值为false下Groovy的真相

编辑2

作为快速说明,您可以更改:

def fos = new FileOutputStream( new File( targetDir, filename ) )
...
Run Code Online (Sandbox Code Playgroud)

至:

new File( targetDir, filename ).withOutputStream { fos ->
  ...
Run Code Online (Sandbox Code Playgroud)

它将确保流为您关闭 :-)