I'm a new to Groovy. I used to use 'try-with-resources' construction in my Java code during work with I/O streams.
Could you please advise, is there any analogue of such construction in Groovy?
The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them. To do so, you must open and use the resource within a Java try-with-resources block.
public interface AutoCloseable. An object that may hold resources (such as file or socket handles) until it is closed. The close() method of an AutoCloseable object is called automatically when exiting a try -with-resources block for which the object has been declared in the resource specification header.
Because a finally block always executes, it typically contains resource-release code. Suppose a resource is allocated in a try block. If no exception occurs, the catch blocks are skipped and control proceeds to the finally block, which frees the resource.
The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java. lang. AutoCloseable , which includes all objects which implement java.
Groovy 2.3 also has withCloseable
which will work on anything that implements Closeable
And Groovy 3+ supports try..with..resources as Java does
https://groovy-lang.org/releasenotes/groovy-3.0.html#_arm_try_with_resources
Have a look at the docs on Groovy IO
and the associated javadoc. It presents the withStream
, withWriter
, withReader
constructions which are means of getting streams with auto-closeability
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With