java7 try-with-resources

     在 java7之前,java的异常处理结构是 try catch finally , try代码块里打开的资源,它们的关闭都得放到finally里,挺繁琐的一个语法规则,相信被广大开发者吐槽过。
     举个简单例子看下:
public static void main(String[] args) {

    File file = new File("/workspace/test.txt") ;
    FileInputStream fis = null ;
    try {
        fis = new FileInputStream(file) ;
        StringBuffer buffer = new StringBuffer() ;
        int c  ;
        while ((c =fis.read()) != -1) {
            buffer.append((char) c) ;
        }
        System.out.print(buffer);
    } catch (FileNotFoundException e) {
        // logging
        // deal exception
    } catch (IOException e) {
        // loggin
        // deal exception
    } finally {
        if(fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // deal exception
            }
        }
    }
}

 

 
从java7开始,默认在语法上支持在try代码块内部默认自动关闭,无须显示的编写代码。
上面例子修改如下:
public static void main(String[] args) {

    File file = new File("/workspace/test.txt") ;
    try (FileInputStream fis = new FileInputStream(file))  {
        StringBuffer buffer = new StringBuffer() ;
        int c  ;
        while ((c =fis.read()) != -1) {
            buffer.append((char) c) ;
        }
        System.out.print(buffer);
    } catch (FileNotFoundException e) {
        // logging
        // deal exception
    } catch (IOException e) {
        // loggin
        // deal exception
    }
}

 

 
这一语法优化,让代码清爽很多。try()内部的代码,默认最后会自动关闭,相当于隐性的执行了finally代码块。
 
java7是怎么做到的,难道对放入try()内部的变量都执行关闭操作,这会不会有问题啊。后面我们发现,java7同时还引入了一个接口
public interface AutoCloseable {
 
    void close() throws Exception;
}

 

而且之前的各种需要关闭的资源类,都实现了这个接口。
这个接口表示,放入try()内部的变量,只要实现了AutoCloseable,jvm默认会自动关闭资源。
 
这再一次表明了接口的强大威力。
 
 
 
posted @ 2016-10-30 15:47  li.zhiliang  阅读(209)  评论(2编辑  收藏  举报