I have a function that downloads files from a web server that is sometimes fed an empty collection. In the function I call each on that collection and what I would expect to happen is that the function just exits with the each closure not being run at all. The problem is that it does get run with an empty filename parameter and the creation of the FileOutputStream goes boom when it is fed 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 does Groovy behave like this and what should I do instead?
It doesn’t, so I assume
filescontains something (likenull?)Assuming it is
nulls in your files List that is causing the issue, you can get rid of them by:Or of course, make the thing that generates the List not add nulls in the first place
Edit
Actually, it sounds like you have a List with empty strings in it…
The
findAllfix should still work, as empty strings evaluate tofalseunder Groovy TruthEdit 2
As a quick note, you can probably change:
to:
And it will ensure the stream is closed for you 🙂