java的try-with-resource处理机制

本文介绍了Java中的try-with-resource机制,如何通过实现Closeable或AutoCloseable接口自动关闭资源,避免了复杂的try-catch结构,提升了代码简洁性,并通过示例展示了其底层实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.描述

资源若实现Closeable或者AutoCloseable接口,则可以在try括号里创建,这样,就会自动调用close()方法去自动关闭资源。这就是try-with-resource机制

2.优点:若不采用机制我们通常需要finallly代码释放资源为了防止报错还要加上try-catch有时候 业务代码 没有 资源释放需要代码采用try-with-resource机制使得代码 变得更加简洁

Closeable继承自AutoCloseable接口,将close函数的Exception异常变为了IOException异常;

3.底层实现

try-with-resource是一种语法糖机制编译器最终实现通过编译可以看到编译器保证resourceclose调用到(在try代码最后以及catch里面调用close从而保证正常执行以及异常 都会调用close);

具体代码方便自己理解如下

import org.junit.jupiter.api.Test;

import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;

public class TryWithResourceTest {
    /***1.自定义资源 ****************************/
    public static class MyCloseResource implements Closeable {
        MyCloseResource() {
            System.out.println("【Closable】-创建");
        }
        @Override
        public void close() throws IOException {
            System.out.println("【Closable】-close");
            throw new IOException("【Closable】-关闭报错");
        }
    }

    @Test
    public void testClosable() {
        try (MyCloseResource r = new MyCloseResource()) {
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    // 反编译后----------
    @Test
    public void testClosable_1() {
        try {
            MyCloseResource r = new MyCloseResource();
            r.close();
        } catch (IOException var2) {
            throw new RuntimeException(var2);
        }
    }

    public static class MyAutoCloseResource implements AutoCloseable {
        MyAutoCloseResource() {
            System.out.println("【AutoCloseable】-创建");
        }
        @Override
        public void close() throws Exception {
            System.out.println("【AutoCloseable】-close");
            throw new Exception("【AutoCloseable】-关闭报错");
        }
    }

    @Test
    public void testAutoCloseable() {
        try (MyAutoCloseResource r = new MyAutoCloseResource()) {
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /****2.单个资源的额情况 *********************/
    @Test
    public void testReadFile2_1() {
        try (FileInputStream fis = new FileInputStream("/Users/data.txt")) {
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Test
    public void testReadFile2_11() {
        try {
            FileInputStream fis = new FileInputStream("/Users/data.txt");
            // 单个资源,会自动调用close
            fis.close();
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }

    @Test
    public void testReadFile2_2() {
        try (FileInputStream fis = new FileInputStream("/Users/data.txt")) {
            // 多个一个输出,会多了一个try-catch代码块
            System.out.println("");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Test
    public void testReadFile2_21() {
        try {
            FileInputStream fis = new FileInputStream("/Users/data.txt");

            try {
                System.out.println("");
            } catch (Throwable var5) {
                try {
                    fis.close();
                } catch (Throwable var4) {
                    var5.addSuppressed(var4);
                }
                throw var5;
            }

            fis.close();
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }



    /***3.多个复杂资源的情况 ****************************************/

    @Test
    public void testReadFile1() {
        try (FileInputStream fis = new FileInputStream("/Users/data.txt");
             BufferedInputStream bis = new BufferedInputStream(fis)) {
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testReadFile11() {
        try {
            FileInputStream fis = new FileInputStream("/Users/data.txt");
            try {
                BufferedInputStream bis = new BufferedInputStream(fis);
                // 会自动调用bis.close
                bis.close();
            } catch (Throwable var5) {
                // bis.close异常会调用这里
                try {
                    // 包在try-catch里面,是因为若是有异常,可以追加到原来的异常里面
                    fis.close();
                } catch (Throwable var4) {
                    var5.addSuppressed(var4);
                }

                throw var5;
            }
            // bis.close没有发生异常,会调用这里
            fis.close();
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值