Dónal
Dónal

Reputation: 187419

automatically closing a resource passed as an argument

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

Upvotes: 9

Views: 1503

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18253

I use Java 8 and it does not support Resource Reference. What about create universal method that accepts Closable and payload:

public static <T extends Closeable> void doAndClose(T out, Consumer<T> payload) throws Exception {
    try {
        payload.accept(out);
    } finally {
        out.close();
    }
}

Client code could look like this:

OutputStream out = null;

doAndClose(out, os -> {
    // do something with the OutputStream
});

InputStream in = null;

doAndClose(in, is -> {
    // do something with the InputStream
});

Upvotes: 3

Mark Rotteveel
Mark Rotteveel

Reputation: 109281

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.

Upvotes: 5

M.F
M.F

Reputation: 443

void doSomething(OutputStream out) {
  try {
    // do something with the OutputStream
  }
  finally {
    org.apache.commons.io.IOUtils.closeQuietly(out);
  }
}

Upvotes: -4

Related Questions