JDK7的Try-catch-resources

先上码

    @Test
    private void TestForNormal() {
        InputStream inputStream = TryCatchDemo.class.getResourceAsStream("/test.md");
        BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String tmpString = null;
        try {
            while ((tmpString = bf.readLine()) != null) {
                sb.append(tmpString);
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bf.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

这是以前最常用的写法对流进行操作,一般来说,在最后都会有一堆嵌套着try-catch的迷之finally用来关闭占用的资源流,忘记关的另说...

语言总是在进步


JDK7 中,出现了一种新的语法糖 try-with-resource
现在,新的语法支持这样玩

 @Test
    public void TestForTryWithResources() {
        try (InputStream inputStream = new FileInputStream("/test.md");
//        InputStream inputStream = TryCatchDemo.class.getResourceAsStream("/test.md")
             BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            StringBuilder sb = new StringBuilder();
            String tmpString = null;
            while ((tmpString = bf.readLine()) != null) {//抛出IOException的地方
                sb.append(tmpString);
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

它的结构是

try( ){
}

关键在

        try (InputStream inputStream = new FileInputStream("/test.md");
//        InputStream inputStream = TryCatchDemo.class.getResourceAsStream("/test.md")
             BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream))
        )

因为括号里头的InputStream ,BufferedReader 都实现了一个AutoCloseable接口,所以无论这段代码是正常执行完,还是有异常往外抛,还是内部代码块发生异常被截获,最终都会按照创建资源的逆顺序,自动关闭资源

实验


    @Test
    public void AutoCloseTest() {
        try (AutoCloseAbleBean autoCloseable = new AutoCloseAbleBean()) {
            throw new RuntimeException("test");
//            autoCloseable.dosomething();
//            return;
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException("test");
        }finally {
            throw new RuntimeException("test");
        }
    }

    class AutoCloseAbleBean implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("i am close");
        }
        void dosomething() {
            System.out.println("before close");
        }
    }

你可能感兴趣的:(JDK7的Try-catch-resources)