JDK7新特性之try-with-resources

JDK7新特性之try-with-resources


本节内容并非JDK8的新特性,而是JDK7的新特性。此处讲解是因为多数人并不知道。

传统方式在资源关闭时,需要对每个需要关闭的资源进行 手动调用close 方法来关闭方法。try-with-resources 方法可以省去传统方式繁琐的步骤,使代码更加简洁。

功能

  • 用于资源关闭。

注意

  • 实现了AutoCloseable接口的类,在try()里声明该类实例的时候,try结束后自动调用的close方法,这个动作会早于finally里调用的方法。
  • 不管是否出现异常,try()里的实例都会被调用close方法。
  • try里面可以声明多个自动关闭的对象,越早声明的对象,会越晚被close掉。

传统方式

public class Main {
    public static void main(String[] args) throws IOException {
        String path = "d:/output.log";
        test(path);

    }

    private static void test(String filepath) throws FileNotFoundException {
        OutputStream out = new FileOutputStream(filepath);
        try {
            out.write((filepath+"可以学习java架构课程").getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

try-with-resources方式

public class Main {
    public static void main(String[] args) {
        test("d:/output.log");
    }
    public static void test(String fileName){
        try(FileOutputStream fileOutputStream = new FileOutputStream(fileName);){
            fileOutputStream.write("小滴课堂".getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

原文地址:https://www.yuque.com/haomingzi-kowv5/pmcs3t/ipzo6r

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值