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?
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?
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
new Socket().withCloseable { socket -> ... }
May 11, 2016 at 6:51
withClosable
works... is there any documentation or anything on it? Most importantly, how do I use it with a java.sql.Connection
or java.sql.Statement
(not my choice - a Java class is returning them to me.)
Sep 5, 2017 at 16:01
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
Simplest try-with-resources for all Groovy versions is the following (even works with AutoCloseable
interface). Where class Thing
is a closeable class or implements AutoCloseable
.
new Thing().with { res ->
try {
// do stuff with res here
} finally {
res.close()
}
}
Which is the equivalent in later versions of Groovy doing:
new Thing().withCloseable { res ->
// do stuff with res here
}