try catch finally? 还是 try with resource?

引言

在程序开发过程中,存在着这样的应用场景:需要读取文件,读取结束之后需要关闭资源;

比如下面的开发场景:

读取了 test.txt 文件,读取结束之后,需要关闭资源,不关闭的话,会造成系统资源的浪费;

public static void main(String[] args) {
    //读取文本文件的内容
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File("/test.txt"));
        while (scanner.hasNext()) {
            System.out.println(scanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

上面的开发方式存在的问题

每次打开一个资源,后面必须关闭一个资源,关闭资源的方式比较麻烦;

如果一个方法中打开了很多的资源之后,开发者可能忘记关闭某个资源;

问题的解决

使用 try - with - resource 可以解决这个问题

public static void tryResource() {
    try (Scanner scanner = new Scanner(new File("test.txt"))) {
        while (scanner.hasNext()) {
            System.out.println(scanner.nextLine());
        }
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    }
}

\

与上面代码块的不同之处在于 try - with - resource 将文件的打开放置到了 try 后面的小括号中;

这样一来,开发者只是需要写 try - catch 语句,不需要在 finally 中释放资源了;

这样做一方面减少了开发者的工作,一方面提升了程序运行的效率;

多个文件的同时打开与关闭

当需要放个文件资源打开的时候,在 try 后面的小括号中使用 ‘;’ 分开即可,如下所示:

public static void tryResourceMulti() {
    try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
         BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
        int b;
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

try catch finally 和 try with resource 语法结构差异

try catch finallytry{

} catch {

} finally {

}
try with resourcetry (书写读取资源的代码,读取结束后自动释放资源) {

} catch {

}

小结

本文比较了 try - catch - finally 与 try - with resource 之间的区别,在开发中,十分推荐使用 try - with - resource 的方法进行资源的打开,因为这样做程序会自动的释放资源,减少开发者的压力。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值