关于Closeable对象的正确关闭

下面的方法将一个文件复制到另一个文件,但是它的设计中存在一个隐患,很难被发现。
static void copy(String src, String dest)throws IOException {
InputStream in = null;
OutputStream out = null; 
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}

如果你还在使用上面这种方式来关闭 Closeable对象的话,那么本文一定会改变你的编程习惯的。
问题在 finally语句中,close方法也可能会抛出IOException异常。如果这正好发现在in.close被调用之时,那么这个异常就会阻止out.close被调用,从而使输出流保持在开放状态
所以这个程序使得 finally可能被意外结束。解决方式是将每一个close都包装在一个try语句块中。从java 5.0版本开始,可以利用Closeable接口:
finally {
closeIgnoringException(in);
closeIgnoringException(out);
}
private static void closeIgnoringException(Closeable c) {
    if (c != null) {
        try {
            c.close();
        } catch (IOException ex) {
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值