If I want to automatically close a resource passed as an argument, is there a more elegant solution than this?
void doSomething(OutputStream out) {
try (OutputStream closeable = out) {
// do something with the OutputStream
}
}
Ideally, I'd like to have this resource closed automatically, without declaring another variable closeable
that refers to the same object as out
.
Aside
I realise that closing out
within doSomething
is considered a bad practice
doSomething
method should not close the input stream itselft. The caller should take care of it. – Barroomout
variable is effectively final). But there's a risk for method parameters, I think. – BoarAutoCloseable
, from the Javadoc: _"All Implemented Interfaces: Closeable, Flushable, AutoCloseable". It directly implementsCloseable
which extendsAutoCloseable
. – ContactAutoCloseable
was introduced in Java 7. Or maybe you've overlooked thatCloseable
is a sub-interface ofAutoCloseable
). – Contact