I have this example:
def fileLocation = '/path/to/my/file.txt'
new FileReader(fileLocation).withCloseable { fileReader ->
new BufferedReader(fileReader).withCloseable{ resource ->
doSomethingWithResource resource
}
}
Is there any way to achieve this in a more compact way, i.e. without nesting withCloseable()
s ? Suppose I need three streams: I would have to nest 3 withCloseable()
s, etc.
This example would not work:
new BufferedReader(new FileReader(fileLocation)).withCloseable{ resource ->
doSomethingWithResource resource
}
as if there is an exception in the outer stream, the inner stream will not be closed.
Note that I could do the following for this over-simplified example:
new File(fileLocation).newReader().withCloseable{ resource ->
doSomethingWithResource resource
}
but this would not work in case we really need to nest streams. What is the best way to achieve this in groovy?