java file 关闭,关于java中关闭流疑问

本文探讨了Java代码中使用ZipOutputStream进行文件压缩时可能遇到的问题。在尝试创建ZipOutputStream实例时,如果在构造函数内部抛出异常,可能导致文件流未正确关闭。作者指出,由于异常发生,finally块中的close方法不会执行,这可能会导致资源泄露。文章通过两个错误放大版代码示例说明了这个问题,并引发了关于这种关闭方式潜在风险的讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面这段代码的作用是压缩,会用到ZipOutputStream

ZipOutputStream zipOutputStream = null;

try {

zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath));

} catch (FileNotFoundException e) {

throw new IllegalArgumentException("zipPath error " + "", e);

} finally {

if (null != zipOutputStream) {

try {

zipOutputStream.close();

} catch (IOException e) {

logger.error("", e);

}

}

}

错误放大版1:

ZipOutputStream zipOutputStream = null;

try {

FileOutputStream fileOutputStream =   new FileOutputStream(zipPath);

throw new RuntimeException();

zipOutputStream = new ZipOutputStream(fileOutputStream);

} catch (FileNotFoundException e) {

throw new IllegalArgumentException("zipPath error " + "", e);

} finally {

if (null != zipOutputStream) {

try {

zipOutputStream.close();

} catch (IOException e) {

logger.error("", e);

}

}

}

错误放大版2:

ZipOutputStream zipOutputStream = null;

try {

zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath),null);

} catch (FileNotFoundException e) {

throw new IllegalArgumentException("zipPath error " + "", e);

} finally {

if (null != zipOutputStream) {

try {

zipOutputStream.close();

} catch (IOException e) {

logger.error("", e);

}

}

}

这里我有一个疑问,在new FileOutputStream(zipPath)的过程中如果已经打开了这个文件,但是在new ZipOutputStream过程中出错了,这个时候zipOutputStream并没有创建成功,所以在finally中不会调用close方法,造成的结果就是这个文件不会被关闭。

所以这种关闭方式是不是会有漏洞,还是我的理由有问题?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值