JDK7 特性之 try-with-resource 资源的自动管理

JDK7 特性之 try-with-resource 资源的自动管理

在java7之前,程序中使用的资源须要被明确地关闭

demo以下html

/**
     * 利用Try-Catch-Finally管理资源(旧的代码风格)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        String filepath = "D:\\gui-config.json";
        BufferedReader br = null;
        String curline;

        try {
            br = new BufferedReader(new FileReader(filepath));
            while ((curline = br.readLine()) != null) {
                System.out.println(curline);

            }
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("文件xxx不存在,请检查后重试。");
            // trturn xxx;
        } catch (IOException e) {
            throw new IOException("文件xxx读取异常。");
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                throw new IOException("关闭流异常。");
            }
        }
    }

try-with-resource 结构(jdk7 新特性)

该try-with资源语句是try声明了一个或多个资源声明。一个资源是程序与它完成后,必须关闭的对象。该try-with资源语句确保每一个资源在发言结束时关闭。java

任何实现的java.lang.AutoCloseable对象(包括实现的全部对象)java.io.Closeable均可以用做资源。json

demo以下oracle

@Test
    public void test2() throws IOException {
        String filepath = "D:\\gui-config.json";

        try (
                FileReader fileReader = new FileReader(filepath);
                BufferedReader br = new BufferedReader(fileReader)
        ) {
            String curline = null;
            while ((curline = br.readLine()) != null) {
                System.out.println(curline);
            }
        }

    }
    // FileReader 和 BufferedReader 均实现了 AutoCloseable 接口

自定义 AutoCloseable 实现类curl

public class AutoCloseTestModel implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("资源管理");
    }

    public void run(boolean flag) {
        if (flag) {
            System.out.println("业务处理");
        } else {
            System.out.println("出现异常");
            throw new RuntimeException("自定义RuntimeException");
        }
    }
}


    @Test
    public void test3() throws Exception {
        try (AutoCloseTestModel autoCloseTestModel = new AutoCloseTestModel()) {
            autoCloseTestModel.run(false);
        }
    }

拓展资料

oracle java 教程 - try-with-resources语句ide

jdk7新特性 try-with-resources 资源的自动管理ui

Java 7中的Try-with-resourcesurl

相关文章
相关标签/搜索