try-with-resource语法

本文深入探讨了Java 7引入的try-with-resource语法,解释了如何利用AutoCloseable接口简化资源管理,避免复杂的finally块。通过具体示例,展示了在文件读写操作中,此语法如何优雅地自动关闭资源,提高代码可读性和安全性。

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

jdk1.7引入了一个语法叫try-with-resource语法,它的使用如下:
如果一个类实现了AutoCloseable接口,并行重写close方法。
那么这个类就可以写在try-catch的try后面的括号中,并且能在try-catch块执行后自动执行这个方法。
举例如下:

public class TryWithResource implements AutoCloseable {

    private int age = 18;

    @Override
    public void close() throws Exception {
        System.out.println("this is close 方法");
    }

    public static void main(String[] args) {
        try (TryWithResource tryWithResource = new TryWithResource()) {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
执行这个方法,我们看到打印结果:
18
this is close 方法
1
2
很明显这样写和下面这种经典写法的效果是一样的,只是看上去能更加简便一些。
public class TryWithResource{

    private int age = 18;

    public void close() throws Exception {
        System.out.println("this is close 方法");
    }

    public static void main(String[] args) {
        TryWithResource tryWithResource = new TryWithResource();
        try {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                tryWithResource.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
这个经典的写法,是不是很熟悉,java编程中很多对于资源的操作,比如文件流等需要连接的资源,都需要在finally中手动关闭资源,但又怕关闭资源抛异常,所以最终就是finally块中又加了try-catch块,这个结构确实怎么看怎么不得劲,但没办法,JDK1.7之前只能只样写。
但是在JDK1.7后,就可以通过接口的方式,优雅的写这些代码了。

举个例子:
默认的java.io.FileReader等类,已经实现了这个接口了,所以我们在操作文件时,就可以直接用这种优雅的方式来写了,
 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config-service-test.xml")
public class FileTest {

    @Test
    public void testFile() {
        write();
        read();
    }

    /**
     * 读
     */
    public void read() {
        String path = "D:\\file\\myFile.txt";
        //Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271
        try (FileReader reader = new FileReader(path);
             BufferedReader br = new BufferedReader(reader)
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                // readLine一行一行读
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 写
     */
    public static void write() {
        try {
            File path = new File("D:\\file\\myFile.txt");
            path.createNewFile();
            try (FileWriter writer = new FileWriter(path);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                out.write("我写入的内容");
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值