Java:try-with-resources语法

郎家岭伯爵 2023年09月20日 320次浏览

前言

打开一个资源使用完后需要手动来关闭资源,有没有什么方法可以在使用完资源后自动关闭资源呢?

try-with-resources 语法可以在代码块执行完毕后自动关闭资源。

实现

手动关闭资源示例

资源在使用完后,我们需要手动来关闭资源。例如我们打开一个 txt 文本资源:

@GetMapping("/t6")
public void test6() throws FileNotFoundException {
    FileReader fr = null;
    BufferedReader br = null;
    try{
        fr = new FileReader("d:/input.txt");
        br = new BufferedReader(fr);
        String s = "";
        while((s = br.readLine()) != null){
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们在 finally 块中手动来关闭了资源。

try-with-resources示例

try-with-resourcesJava 7 中引入的一个语言特性,用于更方便地管理需要手动关闭的资源(例如文件、网络连接、数据库连接等)。它可以在 try 块中自动关闭资源,以确保资源的正确释放,从而避免资源泄漏和提高代码的可维护性。

在这个示例中,我们使用 try-with-resources 语法来关闭资源:

@GetMapping("/t7")
public void test7() throws FileNotFoundException {
    try(
        FileReader fr = new FileReader("d:/input.txt");
        BufferedReader br = new BufferedReader(fr)
    ){
        String s = "";
        while((s = br.readLine()) != null){
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

在这里示例中,我们在 try-with-resources 块中声明了多个资源,那么它们会按照声明的顺序逐个进行关闭

拓展

任何实现了 java.lang.AutoCloseable 的对象, 包括所有实现了 java.io.Closeable 的对象,都可以用作一个资源。

也就是说,任何实现了 java.lang.AutoCloseable 的对象, 包括所有实现了 java.io.Closeable 的对象,都可以通过 try-with-resources 关闭。

自定义对象示例

我们来自定义一个对象,同时实现 java.lang.AutoCloseable 接口:

package com.langjialing.helloworld.model;

/**
 * @author 郎家岭伯爵
 * @time 2023/9/20 9:57
 */
public class MyAutoClosable implements AutoCloseable {
    public void doIt() {
        System.out.println("MyAutoClosable doing it!");
    }

    @Override
    public void close() throws Exception {
        System.out.println("MyAutoClosable closed!");
    }
}

然后我们在 try-with-resources 代码块中使用:

@GetMapping("t8")
public void test8(){
    try(MyAutoClosable myAutoClosable = new MyAutoClosable()){
        myAutoClosable.doIt();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用 POSTMAN 调用方法后的输出:

MyAutoClosable doing it!
MyAutoClosable closed!

总结

在 Java 7 中引入的 try-with-resources 语法,在资源使用结束后可以自动地关闭资源。

赞助页面示例