原创  Java中Stream的close 收藏

 最近在精简代码,发现每次new一个ByteArrayInputStream然后再new一个DataInputStream,然后还要把两个都close,看着都恶心,真的要这么写吗?

首先,实在搞不懂为什么ByteArrayInputStream也要close,完全没有意义吗!好在现在java也开源了,看了一下源代码,发现close还真是多余的:

  1.     /**
  2.      * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in
  3.      * this class can be called after the stream has been closed without
  4.      * generating an <tt>IOException</tt>.
  5.      * <p>
  6.      */
  7.     public void close() throws IOException {
  8.     }

 

然后再说DataInputStream的close,如果是和File或者Socket关联的,close还真是有意义的,如果是和ByteArrayInputStream关联的,close就没有必要。猜也能猜出来会怎样实现,看了源码果然:

  1.    /**
  2.      * Closes this input stream and releases any system resources 
  3.      * associated with the stream. 
  4.      * This
  5.      * method simply performs <code>in.close()</code>.
  6.      *
  7.      * @exception  IOException  if an I/O error occurs.
  8.      * @see        java.io.FilterInputStream#in
  9.      */
  10.     public void close() throws IOException {
  11.     in.close();
  12.     }

 

结论:

如果是InputStream--->DataInputStream这样构建出来的,只要调用DataInputStream的close就可以了。

更为精简的做法是,如果从ByteArrayInputStream构建出来的,谁的close都不需要调用。

发表于 @ 2008年12月30日 09:25:00 | 评论( loading... ) | 编辑| 举报| 收藏

旧一篇:在Lua中使用Unicode | 新一篇:J2ME中Form的内存泄露

  • 发表评论
  • 评论内容:
  •  
Copyright © happycock
Powered by CSDN Blog