我可以关闭底层输出流并让装饰器 BufferedOutputStream 未关闭吗
Can I close underlying outputstream and let the decorator BufferedOutputStream unclosed
我有一个
的多个实现
void convert(List< InputStream > list, OutputStream os)
方法。
给定的资源可以重复使用,因此不会被方法实现释放。但是,在某些情况下,我想用 BufferedOutputStream 装饰给定的输出流。
关闭装饰器将导致关闭我想要避免的底层流。
我的问题是:我可以安全地让装饰器解锁并让调用方法管理底层流释放吗?
装饰 classes 通常不会打开必须关闭以防止资源泄漏的系统资源(如操作系统文件句柄)。给定的 OutputStream
参数必须关闭(因为它可能与打开的系统资源相关联),但正如您提到的,这是调用者的责任。
但是如果不关闭修饰 class,则必须处理通常发生在 close()
方法中的方法调用。在 BufferedOutputStream
you can see that flush()
is called in the super class FilterOutputStream
close()
方法的情况下。
为了容纳这些缺失的方法调用,创建一个单独的 NonClosingBufferedOutputStream
class 扩展 BufferedOutputStream
,其中包含 close()
方法的修改版本 [=14] =](只需注释掉 out.close();
行)。您现在可以将此 class 用作普通 Closeable
并避免来自您的 IDE/compiler.
的警告
我打算推荐使用 CloseShieldOutputStream
from Apache commons-io, but looking at the source code, it appears that flush()
is not called in the close()
method. Despite this shortcoming, replacing the underlying outputstream with a ClosedOutputStream
似乎是个好主意:它会更快地显示编程错误。
请注意,对于 class 等其他装饰 GZIPOutputStream
,除 flush()
之外的其他方法可能也是合适的。在 GZIPOutputStream
的情况下,使用调用 finish()
的修改后的 close()
方法创建 NonClosingGZIPOutputStream
class 可以解决问题。
我有一个
的多个实现 void convert(List< InputStream > list, OutputStream os)
方法。
给定的资源可以重复使用,因此不会被方法实现释放。但是,在某些情况下,我想用 BufferedOutputStream 装饰给定的输出流。
关闭装饰器将导致关闭我想要避免的底层流。
我的问题是:我可以安全地让装饰器解锁并让调用方法管理底层流释放吗?
装饰 classes 通常不会打开必须关闭以防止资源泄漏的系统资源(如操作系统文件句柄)。给定的 OutputStream
参数必须关闭(因为它可能与打开的系统资源相关联),但正如您提到的,这是调用者的责任。
但是如果不关闭修饰 class,则必须处理通常发生在 close()
方法中的方法调用。在 BufferedOutputStream
you can see that flush()
is called in the super class FilterOutputStream
close()
方法的情况下。
为了容纳这些缺失的方法调用,创建一个单独的 NonClosingBufferedOutputStream
class 扩展 BufferedOutputStream
,其中包含 close()
方法的修改版本 [=14] =](只需注释掉 out.close();
行)。您现在可以将此 class 用作普通 Closeable
并避免来自您的 IDE/compiler.
我打算推荐使用 CloseShieldOutputStream
from Apache commons-io, but looking at the source code, it appears that flush()
is not called in the close()
method. Despite this shortcoming, replacing the underlying outputstream with a ClosedOutputStream
似乎是个好主意:它会更快地显示编程错误。
请注意,对于 class 等其他装饰 GZIPOutputStream
,除 flush()
之外的其他方法可能也是合适的。在 GZIPOutputStream
的情况下,使用调用 finish()
的修改后的 close()
方法创建 NonClosingGZIPOutputStream
class 可以解决问题。