最近在精简代码,发现每次new一个ByteArrayInputStream然后再new一个DataInputStream,然后还要把两个都close,看着都恶心,真的要这么写吗?
首先,实在搞不懂为什么ByteArrayInputStream也要close,完全没有意义吗!好在现在java也开源了,看了一下源代码,发现close还真是多余的:
- /**
- * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in
- * this class can be called after the stream has been closed without
- * generating an <tt>IOException</tt>.
- * <p>
- */
- public void close() throws IOException {
- }
然后再说DataInputStream的close,如果是和File或者Socket关联的,close还真是有意义的,如果是和ByteArrayInputStream关联的,close就没有必要。猜也能猜出来会怎样实现,看了源码果然:
- /**
- * Closes this input stream and releases any system resources
- * associated with the stream.
- * This
- * method simply performs <code>in.close()</code>.
- *
- * @exception IOException if an I/O error occurs.
- * @see java.io.FilterInputStream#in
- */
- public void close() throws IOException {
- in.close();
- }
结论:
如果是InputStream--->DataInputStream这样构建出来的,只要调用DataInputStream的close就可以了。
更为精简的做法是,如果从ByteArrayInputStream构建出来的,谁的close都不需要调用。