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
.
I realise that closing out
within doSomething
is considered a bad practice
With Java 9 and higher, you can do
void doSomething(OutputStream out) {
try (out) {
// do something with the OutputStream
}
}
This is only allowed if out
is final or effectively final. See also the Java Language Specification version 10 14.20.3. try-with-resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With