8

如果我想自动关闭作为参数传递的资源,还有比这更优雅的解决方案吗?

void doSomething(OutputStream out) {

  try (OutputStream closeable = out) {
    // do something with the OutputStream
  }
}

理想情况下,我希望自动关闭此资源,而无需声明另一个closeable引用相同对象的变量out

在旁边

我意识到关闭out内部doSomething被认为是一种不好的做法

4

3 回答 3

5

使用 Java 9 及更高版本,您可以

void doSomething(OutputStream out) {
  try (out) {
    // do something with the OutputStream
  }
}

仅当out是最终的或有效的最终时才允许这样做。另请参阅Java 语言规范版本 10 14.20.3。尝试资源

于 2018-08-14T09:37:33.130 回答
3

我使用 Java 8,它不支持资源引用。创建接受Closable和有效负载的通用方法怎么样:

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

客户端代码可能如下所示:

OutputStream out = null;

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

InputStream in = null;

doAndClose(in, is -> {
    // do something with the InputStream
});
于 2018-08-14T09:48:43.843 回答
-4
void doSomething(OutputStream out) {
  try {
    // do something with the OutputStream
  }
  finally {
    org.apache.commons.io.IOUtils.closeQuietly(out);
  }
}
于 2018-08-14T09:28:20.560 回答