try-with-resource

傳統的io操做基本上都有相似下面的寫法ide

private static void traditionalMethod() {
        InputStream input = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            input = new FileInputStream("d:/test.txt");
            bufferedInputStream = new BufferedInputStream(input);
            doSomeHandle(bufferedInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

try-catch-finally;
try裏打開資源; catch捕捉一些可能的異常,如文件不存在。IOException等 finally裏面要關閉資源;關閉資源的時候又要try catch。。code

jdk7裏新增了 try-with-resource的模式資源

/* since jdk 1.7 */
    private static void modernMethod() {
        try (
                InputStream input = new FileInputStream("d:/test.txt");
                BufferedInputStream bufferedInputStream = new BufferedInputStream(input);
        ) {
            doSomeHandle(bufferedInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

全部實現input

AutoCloseable

的類在使用完以後都會自動關閉資源;it

咱們能夠本身實現一個AutoCloseableio

public class MyAutoCloseable implements  AutoCloseable {

    public void doSome(){
        System.out.println("一些其餘的操做");
    }

    @Override
    public void close() throws Exception {
        System.out.println("關閉資源。。。");
    }
}

而後看看try-with-resource的過程class

try (
                MyAutoCloseable resource = new MyAutoCloseable()
        ) {
            resource.doSome();
        } catch (Exception e) {
            e.printStackTrace();
        }

打印結果以下test

一些其餘的操做
關閉資源。。。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息