今天写文件压缩,需要使用到输入输出流所以finally的好处体现出来了
finally{}中的代码不管是否会发生异常都会执行,将流的关闭放在这里面,避免资源浪费,从而提高系统性能。
如果多个流需要关闭,则在
finally{
try { if (out != null) { out.close();// 如果此处出现异常,则out2流也会被关闭 } } catch (Exception e) { e.printStackTrace(); } try { if (out2 != null) { out2.close(); } } catch (Exception e) { e.printStackTrace(); }
}
----参考:https://www.cnblogs.com/tongxuping/p/8192073.html
注意:在循环中创建流,在循环外关闭,导致关闭的是最后一个流(这种情况可能发生在自己身上)
应该在循环内创建的应该在循环内关闭:
for (int i = 0; i < 10; i++) {
OutputStream out = null;
try {
out = new FileOutputStream("");
// ...操作流代码
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}