Java Try...Catch...Finally在Java 6 与Java 7的变化

来源:互联网 发布:linux 重启后 svn失效 编辑:程序博客网 时间:2024/06/06 18:51

在Java程序编写过程中,使用大量的Try…Catch…Finally框架。例如,在使用openStream()方法连接到URL所引用的资源时,在客户端与服务器之间完成必要的握手,返回一个InputStream,可以由此读取数据。
在Java 6版本之前,整个过程代码如下:

import java.io.InputStream;import java.net.URL;public class URLOpenStream {    public static void main(String[] args) {        InputStream in = null;        try {            URL url = new URL("http://www.baidu.com");            in = url.openStream();            int c;            while ((c = in.read()) != -1) {                System.out.write(c);            }        } catch (Exception e) {            // TODO: handle exception            System.out.println(e);        } finally {            try {                if (in != null) {                    in.close();                }            } catch (Exception e2) {                // TODO: handle exception                System.out.println(e2);            }        }    }}
在Java 7以后更为简洁,可以使用一个嵌套的try-with-resources语句:
import java.io.IOException;import java.io.InputStream;import java.net.URL;public class URLOpenStream {    public static void main(String[] args) {        try {            URL url = new URL("http://www.baidu.com");            try (InputStream in = url.openStream()) {                int c;                while ((c = in.read()) != -1) {                    System.out.write(c);                }            }        } catch (IOException e) {            // TODO: handle exception            System.out.println(e);        }    }}

可以看出,Java 7以后编写方式更为简洁,因为Java 7改写了所有的IO资源类,它们都实现了AutoCloseable接口,因此都可以通过自动关闭资源的try语句来自动关闭这些IO流。
在try()内的对象是临时变量,当调用完毕以后,自动被回收。有些说是将会比手动catch内关闭IO流,速度快,实际是否较快并未实际测试。。。。hah

原创粉丝点击