转自:https://blog.csdn.net/u012668925/article/details/53941471
在解压图片的时候发现ByteArrayOutputStream不需要关闭,为啥呢?
ByteArrayOutputStream或ByteArrayInputStream是内存读写流,不同于指向硬盘的流,它内部是使用字节数组读内存的,这个字节数组是它的成员变量,当这个数组不再使用变成垃圾的时候,Java的垃圾回收机制会将它回收。所以不需要关流。如下图所示,ByteArrayOutputStream内部是数组:
然后再看看FileOutputStream的构造:
很明显FileOutputStream的构造方法打开了IoBridge,
也就是说,指向内存的流可以不用关闭,指向存储卡/硬盘的流一定要关闭。
通过ByteArrayInputStream和ByteArrayOutputStream的源码close()方法也可以发现,调用它们的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>.
*/
public void close() throws IOException {
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*/
public void close() throws IOException {
}
最后
不过我的建议是只要是流,用完后都在finally块里调用其close()方法进行关闭。万一哪天你记混了,认为ObjectOutputSteam不需要close,项目上生产环境出了问题,相信我,你会哭的!