try-with-resource例子

try-with-resource可以帮我们管理资源如关闭IO流,Socket。在try-catch语句块中不用我们手写冗长的finally代码。

1.写在try()中的外部资源句柄必须实现了AutoCloseable接口。
 在try()里的语句不能是任意一个赋值语句,new出来或者其他方式初始化的对象必须实现AutoCloseable接口,
 我们经常需要try-catch-finally的IO,Socket这块的类都已经实现了AutoCloseable接口。如字节流父类InputStream,OutputStream
 我们在操作它子类时候就可以使用try-with-resource
 
 2.try()中可以定义多个赋值语句,多个语句之间用分号分隔,最后一个语句后面不要带分号,如下例子。
	//jdk7的try-with-resource,不用自己写finally关闭资源      
    try (FileInputStream fs = new FileInputStream(new File(""));
         FileOutputStream fo = new FileOutputStream(new File(""))) {
        //do somthing.....
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //传统方式
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(new File(""));
        //do somthing.....
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值