Java之IO流的关闭

1.在finally中关闭流;

OutputStream out = null;  
try {  
    out = new FileOutputStream("");  
    // ...操作流代码  
} catch (Exception e) {  
    e.printStackTrace();  
} finally {  
    try {  
        if (out != null) {  
            out.close();  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

 

2.在关闭多个流时因为嫌麻烦将所有关流的代码丢到一个try中

OutputStream out = null;  
OutputStream out2 = null;  
try {  
    out = new FileOutputStream("");  
    out2 = new FileOutputStream("");  
    // ...操作流代码  
} catch (Exception e) {  
    e.printStackTrace();  
} finally {  
    try {  
        if (out != null) {  
            out.close();// 如果此处出现异常,则out2流也会被关闭  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
    try {  
        if (out2 != null) {  
            out2.close();  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

 

3.在循环中创建流,在循环外关闭,导致关闭的是最后一个流

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();  
        }  
    }  
}  

 

4.在Java7中,关闭流这种繁琐的操作就不用我们自己写了

  只要实现的自动关闭接口(Closeable)的类都可以在try结构体上定义,java会自动帮我们关闭,及时在发生异常的情况下也会。可以在try结构体上定义多个,用分号隔开即可,如:

try (OutputStream out = new FileOutputStream("");OutputStream out2 = new FileOutputStream("")){  
    // ...操作流代码  
} catch (Exception e) {  
    throw e;  
}  

 

转载于:https://www.cnblogs.com/tongxuping/p/8192073.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值