Java Try...Catch...Finally在Java 6 与Java 7的变化,
分享于 点击 14616 次 点评:260
Java Try...Catch...Finally在Java 6 与Java 7的变化,
在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
相关文章
- 暂无相关文章
用户点评