Groovy, try with resources alternative

I am new to Groovy. I used to use the try-with-resources construct in my Java code while working with I / O streams.

Could you advise if there is any analogue of such a construction in Groovy?

+53
groovy
Apr 30 '14 at 7:25
source share
3 answers

Check out the docs on Groovy IO and related Javadoc. It presents the constructions withStream , withWriter , withReader which are a means of receiving threads with automatic closure

+29
Apr 30 '14 at 7:32
source share

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

+49
Apr 30 '14 at 8:23
source share

The simplest attempt to use resources for all versions of Groovy is as follows (it even works with the AutoCloseable interface). Where the Thing class is a AutoCloseable class or implements AutoCloseable .

 new Thing().with { res -> try { // do stuff with res here } finally { res.close() } } 

Which is equivalent in later versions of Groovy:

 new Thing().withCloseable { res -> // do stuff with res here } 
0
Apr 12 '19 at 4:41
source share



All Articles