Why is each close of an empty empty collection performed at least once?

I have a function that downloads files from a web server, which sometimes gets an empty collection. In the function that I call each of this collection, and what I expect to happen, is that the function just exits, with each closure not being performed at all. The problem is that it starts with an empty filename parameter, and the creation of FileOutputStream is booming when it is loaded into a directory instead of a file.

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

Why is Groovy acting like this and what should I do instead?

+7
source share
1 answer

This is not the case, so I assume that files contains something (e.g. null ?)

 [].each { println "boom" // This doesn't appear } [null].each { println "pow!" // this does } 

Assuming your files have a null list causing the problem, you can get rid of them:

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

Or, of course, do what the list generates without first adding zeros.

Edit

Actually, it looks like you have a list with empty lines in it ...

findAll should still work as empty lines are evaluated to false in Groovy Truth

Edit 2

As a quick note, you can probably change:

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

in

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

And it ensures that the stream is closed to you :-)

+10
source

All Articles