自动关闭作为参数传递的资源
automatically closing a resource passed as an argument
如果我想自动关闭作为参数传递的资源,有没有比这更优雅的解决方案?
void doSomething(OutputStream out) {
try (OutputStream closeable = out) {
// do something with the OutputStream
}
}
理想情况下,我希望自动关闭此资源,而不声明另一个引用与 out
相同对象的变量 closeable
。
旁白
我意识到在 doSomething
内关闭 out
被认为是一种不好的做法
void doSomething(OutputStream out) {
try {
// do something with the OutputStream
}
finally {
org.apache.commons.io.IOUtils.closeQuietly(out);
}
}
使用 Java 9 及更高版本,您可以做到
void doSomething(OutputStream out) {
try (out) {
// do something with the OutputStream
}
}
仅当 out
是最终的或实际上是最终的时才允许这样做。另见 Java Language Specification version 10 14.20.3. try-with-resources.
我用的是Java8,不支持资源引用。如何创建接受 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
});
如果我想自动关闭作为参数传递的资源,有没有比这更优雅的解决方案?
void doSomething(OutputStream out) {
try (OutputStream closeable = out) {
// do something with the OutputStream
}
}
理想情况下,我希望自动关闭此资源,而不声明另一个引用与 out
相同对象的变量 closeable
。
旁白
我意识到在 doSomething
内关闭 out
被认为是一种不好的做法
void doSomething(OutputStream out) {
try {
// do something with the OutputStream
}
finally {
org.apache.commons.io.IOUtils.closeQuietly(out);
}
}
使用 Java 9 及更高版本,您可以做到
void doSomething(OutputStream out) {
try (out) {
// do something with the OutputStream
}
}
仅当 out
是最终的或实际上是最终的时才允许这样做。另见 Java Language Specification version 10 14.20.3. try-with-resources.
我用的是Java8,不支持资源引用。如何创建接受 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
});