java 嵌套流关闭_关于java IO嵌套流关闭问题

流的关闭

在java language嵌套流中,不凡大众对关闭嵌套流均是由内而外的关闭,但是看如下jdk源码:

/*

* %W% %E%

*

* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.

* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.

*/

package java.io;

/**

* This class is the superclass of all classes that filter output

* streams. These streams sit on top of an already existing output

* stream (the underlying output stream) which it uses as its

* basic sink of data, but possibly transforming the data along the

* way or providing additional functionality.

*

* The class FilterOutputStream itself simply overrides

* all methods of OutputStream with versions that pass

* all requests to the underlying output stream. Subclasses of

* FilterOutputStream may further override some of these

* methods as well as provide additional methods and fields.

*

* @author Jonathan Payne

* @version %I%, %G%

* @since JDK1.0

*/

public

class FilterOutputStream extends OutputStream {

/**

* The underlying output stream to be filtered.

*/

protected OutputStream out;

/**

* Creates an output stream filter built on top of the specified

* underlying output stream.

*

* @param out the underlying output stream to be assigned to

* the field this.out for later use, or

* null if this instance is to be

* created without an underlying stream.

*/

public FilterOutputStream(OutputStream out) {

this.out = out;

}

/**

* Flushes this output stream and forces any buffered output bytes

* to be written out to the stream.

*

* The flush method of FilterOutputStream

* calls the flush method of its underlying output stream.

*

* @exception IOException if an I/O error occurs.

* @see java.io.FilterOutputStream#out

*/

public void flush() throws IOException {

out.flush();

}

/**

* Closes this output stream and releases any system resources

* associated with the stream.

*

* The close method of FilterOutputStream

* calls its flush method, and then calls the

* close method of its underlying output stream.

*

* @exception IOException if an I/O error occurs.

* @see java.io.FilterOutputStream#flush()

* @see java.io.FilterOutputStream#out

*/

public void close() throws IOException {

try {

flush();

} catch (IOException ignored) {

}

out.close();

}

}

这是jdk1.6 中FilterOutputStream流的部分实现代码(我是粘贴过来的)。从这段代码可以看出,嵌套流关闭时直接关闭的是被封装流,只是在关闭之前flush。

总结:(查看大部分的jdk源码后)嵌套流的关闭内部的流和封装流的效果是一样的,没有必要对每层流均进行close,产生让人眼花缭乱的冗余代码(注:本部分说的是jdk中的流,不排除第三方个人和组织的封装流)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值