我是Groovy的新手。在处理I/O流时,我经常在Java代码中使用“try- with -resources”结构。
您能建议一下,在Groovy中有类似的构造吗?
发布于 2014-04-30 15:32:34
看看the docs on Groovy IO和相关的javadoc。介绍了withStream、withWriter、withReader结构,它们是获取具有自动闭合性的流的方法
发布于 2014-04-30 16:23:57
Groovy2.3还提供了可以在任何实现Closeable的平台上运行的withCloseable
Groovy 3新闻快讯
Groovy和3+一样支持try..with..resources
https://groovy-lang.org/releasenotes/groovy-3.0.html#_arm_try_with_resources
发布于 2019-04-12 12:41:01
下面是所有Groovy版本的最简单的try- with -resources (甚至可以使用AutoCloseable接口)。其中,类Thing是一个可关闭的类或实现了AutoCloseable。
new Thing().with { res ->
try {
// do stuff with res here
} finally {
res.close()
}
}这在Groovy的后续版本中是等效的:
new Thing().withCloseable { res ->
// do stuff with res here
}https://stackoverflow.com/questions/23382079
复制相似问题