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

一些其余的操做
关闭资源。。。
本站公众号
   欢迎关注本站公众号,获取更多信息