锁定老帖子 主题:会议室中讨论java I/O流的关闭问题
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-04-09
最后修改:2009-05-20
...... InputStream is = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { is = new FileInputStream(lfm.loadFile(req)); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(resp.getOutputStream()); byte[] buf = new byte[1024]; int len = bis.read(buf); while (len != -1) { bos.write(buf, 0, len); len = bis.read(buf); } bos.flush(); } catch (FileNotFoundException e) { resp.getWriter().write("请求的资源文件不存在...."); } finally { if (bis != null) { bis.close(); bis = null; } if (bos != null) { bos.close(); bos = null; } } ...... 对上面代码中的 is的是否被关闭, 程序员A,程序员B,程序员C,程序员D,展开讨论:
程序员A说:该段代码运行完后,is不会关闭,应该在finally代码段中明确加入如下代码 if (is != null) { is.close(); is = null; } is才会被关闭。
--------------------------------------------------------------------------------------------------------------------------------------------------------------- 程序员B说:该段代码运行完后,is是会被关闭的,下面是他的理由
从设计模式上看: java.io.BufferedInputStream是java.io.InputStream的装饰类。 BufferedInputStream装饰一个 InputStream 使之具有缓冲功能,is要关闭只需要调用最终被装饰出的对象的 close()方法即可,因为它最终会调用真正数据源对象的 close()方法。
BufferedInputStream的close方法中对InputStream进行了关闭,下面是jdk中附带的源代码: public void close() throws IOException { byte[] buffer; while ( (buffer = buf) != null) { if (bufUpdater.compareAndSet(this, buffer, null)) { InputStream input = in; in = null; if (input != null) input.close(); return; } // Else retry in case a new buf was CASed in fill() } 他还把java.io.BufferedInputStream的api搬出来: closepublic void close () throws IOException
Closeable
中的 close
FilterInputStream
中的 close
IOException
- 如果发生 I/O 错误。FilterInputStream.in
-------------------------------------------------------------------------------------------------------------------------------------------------------------------- 程序员C说:在我们不知道是否会关闭的情况下,最好是显式关闭。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 1982 次