English 中文(简体)
为什么每个空收藏的关闭都要至少运行一次?
原标题:Why does an each closure over an empty collection run at least once?
  • 时间:2012-05-28 09:48:08
  •  标签:
  • groovy

我有一个从网络服务器下载文件的功能, 有时会输入一个空收藏 。 在函数中, 我将每个功能调用到该收藏以及我所期望的会发生的情况是, 函数只需退出每个关闭点, 而每个关闭点根本没有运行 。 问题在于它会以空 < code> filename 参数运行, 而当输入目录而不是文件时, 文件 OutputStream 的创建会自动启动 。

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

为什么格罗维会这样? 我该怎么做?

最佳回答

它没有,所以我想files 包含某种东西(如 null ? )

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

[null].each {
  println "pow!"  // this does
}

假设造成问题的是您文件列表中 null ,您可以通过下列方式摆脱这些问题:

files.findAll().each { filename ->
  def fos = new FileOutputStream( new File( targetDir, filename ) )
  ...

或者,当然,让产生清单的东西不要首先增加空格。

Edit

实际上,听起来你有一个清单 里面空空的字符串...

finddAll findAll/code> findAll 应仍然有效, 因为空字符串根据 Groovy Truth 评估 false

Edit 2

简而言之,你或许可以改变:

def fos = new FileOutputStream( new File( targetDir, filename ) )
...

至:

new File( targetDir, filename ).withOutputStream { fos ->
  ...

http://groovy.codehaus.org/groovy-jdk/java/io/File. html#与OutputStream%28groovy.lang.

问题回答

暂无回答




相关问题
Groovy - how to exit each loop?

I m new to Grails/Groovy and am trying to find a node in a an xml file; I ve figured out how to iterate over all of them, but I want to exit the loop when the target node is found. I ve read that ...

Eclipse Spring Builder set properties with Groovy beans

I typically use groovy to construct simple bean but the Spring IDE plugin to eclipse fails to build when I try to set a property that is generated by groovy without an explicit setter. For example, ...

How can I get this snippet to work?

I d like to port a little piece of code from Ruby to Groovy, and I m stuck at this: def given(array,closure) { closure.delegate = array closure() } given([1,2,3,4]) { findAll { it > 4} ...

Changing the value in a map in Groovy

This is about a very basic program I m writing in Groovy. I have defined a map inside a method: def addItem() { print("Enter the item name: ") def itemName = reader.readLine() print(...

Is functional Clojure or imperative Groovy more readable?

OK, no cheating now. No, really, take a minute or two and try this out. What does "positions" do? Edit: simplified according to cgrand s suggestion. (defn redux [[current next] flag] [(if flag ...

热门标签