Java中try-with-resources的使用

        try-with-resources是Java7中加入的,大大简化的对资源的管理,而且使用try-with-resources的代码清晰易懂

1、传统ry-catch-finally的写法

        在管理多资源的时候尤其恐怖,如下:

    /**
     * 手动关闭
     */
    public static void test1() {
        String filePath = "D:\\test1\\test1.txt";
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(filePath));
            fileInputStream = new FileInputStream(new File(filePath));
            // 写
            fileOutputStream.write("ab1024".getBytes(Charset.defaultCharset()));
            // 读取
            int data = fileInputStream.read();
            while (data != -1) {
                System.out.print((char) data);
                data = fileInputStream.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭写流
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 关闭读流
                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
 
        }
    }

2、try-with-resources写法:

/**
 * 自动关闭 try-with-resource
 */
public static void test2() throws Exception {
    String filePath = "D:\\test1\\test1.txt";
    // java7中的try-with-resource,java9中有所改善
    try (FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
         FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
        // 写
        fileOutputStream.write("ab1024".getBytes(Charset.defaultCharset()));
        // 读取
        int data = fileInputStream.read();
        while (data != -1) {
            System.out.print((char) data);
            data = fileInputStream.read();
        }
        // 模拟异常
      //  int a = 0 / 0;
    }
}

可以看出,精简了不少。

Java9对其进行了简单的优化,使用起来更加便捷;

// Java9可以这样写        
FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
try (fileOutputStream;fileInputStream) {
     // .......
}

        原理当try中代码执行结束后(正常结束或者异常结束),都会调用try()括号中对象的close()方法来关闭资源

        可以自己使用main方法测试,模拟抛出异常,捕获异常后对未关闭流的文件进行重命名或者删除操作,未关闭的文件是不能操作的,操作成功说明关闭成功。

3、实践

package onlytest;

import static java.lang.System.out;

public class testAutoClose {

    public static void main(String[] args) {
        try (MyClose close = new MyClose()) {
            close.println("liuqinhou");
            throw new Throwable("exist error");
        } catch (Exception e) {
            out.println("exception exists");
            e.printStackTrace();
        } catch (Throwable throwable) {
            out.println("throwable exists");
            throwable.printStackTrace();
        }
        out.println("main thread end");
    }
}

class MyClose implements AutoCloseable {

    public void println(String str) {
        out.println(str + " is working...");
    }

    @Override
    public void close() throws Exception {
        out.println("MyClose is closed now");
    }
}

输出结果为:

liuqinhou is working...
MyClose is closed now //try中代码执行后会立马执行resource对象的close方法,如果发生了异常,再执行catch中的语句
throwable exists
main thread end
java.lang.Throwable: exist error
	at onlytest.testAutoClose.main(testAutoClose.java:10)

Process finished with exit code 0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值