Java中try-with-resources的使用

本文介绍了Java 7引入的try-with-resources特性,它使得资源管理更加简洁和易于理解。通过对比传统的try-catch-finally与try-with-resources的代码示例,展示了后者如何有效地自动关闭资源,减少了手动关闭的繁琐步骤。在Java 9中,这一特性得到了进一步优化,允许在同一try语句中处理多个资源。文章还提供了测试方法以验证资源是否正确关闭。
摘要由CSDN通过智能技术生成

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方法测试,模拟抛出异常,捕获异常后对未关闭流的文件进行重命名或者删除操作,未关闭的文件是不能操作的,操作成功说明关闭成功。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值