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?
Java's try-with-resources is also in Groovy as of version 3.
Your example would become
In effect, if you have multiple statements in a try-with-resources, the compiler will generate nested try-finally blocks for each of them.
Closing the BufferedReader will close the underlying FileReader (see 1388602 ). But you're right in the circumstance where the BufferedReader constructor fails with an exception, the FileReader would not be closed. So there's some danger of a resource leak if you do as you said