Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy, "try-with-resources" construction alternative

Tags:

groovy

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?

like image 480
XZen Avatar asked Apr 30 '14 07:04

XZen


People also ask

Does try with resources close stream?

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.

What do you mean by auto closeable resources?

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.

How do you release a resource in Java?

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.

Which language feature ensures that objects implementing the AutoCloseable interface are closed?

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.


2 Answers

Groovy 2.3 also has withCloseable which will work on anything that implements Closeable

Groovy 3 newsflash

And Groovy 3+ supports try..with..resources as Java does

https://groovy-lang.org/releasenotes/groovy-3.0.html#_arm_try_with_resources

like image 182
tim_yates Avatar answered Sep 21 '22 13:09

tim_yates


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

like image 29
Grooveek Avatar answered Sep 22 '22 13:09

Grooveek