try-with的使用

使用传统的try-catch,需要手动关闭打开的资源,finally中还需要对资源先进行判空再关闭,比较繁琐,示例代码如下

private void correctWriting() throws IOException {
       DataOutputStream out = null;
       try {
           out = new DataOutputStream(new FileOutputStream("data"));
           out.writeInt(666);
           out.writeUTF("Hello");
       } finally {
           if (out != null) {
               out.close();
           }
       }        
   }

try-with是JDK7后推出的语法糖,可以自动关闭打开的资源,如果想使用try-with,资源类必须实现AutoCloseable接口

@Test
public void getCourses() {
    String url="jdbc:mysql:///cgb2109";
//使用try with语法糖需要在try的括号中打开资源,如果有多个资源,用分号间隔
    try (Connection conn=DriverManager.getConnection(url,"root","root");
         Statement state=conn.createStatement();){
        ResultSet res=state.executeQuery("select * from courses");
        while(res.next()){
            for (int i = 1; i <=3; i++) {
                System.out.print(res.getObject(i)+"\t");
            }
            System.out.println();
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }

 如何查看try  with是否有自动执行close(),可以让某个类实现AutoCloseable接口,并重写其中的close方法,如果自动关闭资源,会执行这个重写的close方法,示例代码如下

public class Test2 {
    public static void main(String[] args) {
        try(close_demo cd=new close_demo()){
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
class close_demo implements AutoCloseable{
    @Override
    public void close() throws Exception {//重写此方法后,在try with类的资源使用结束后会自动调用close方法来关闭资源
        System.out.println("关闭");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值