Java try-with-resource语法使用解析语法使用解析
主要介绍了Java try-with-resource语法使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具
有一定的参考学习价值,需要的朋友可以参考下
背景背景
众所周知,所有被打开的系统资源,比如流、文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运
行,资源泄露将会累积成重大的生产事故。
在Java的江湖中,存在着一种名为finally的功夫,它可以保证当你习武走火入魔之时,还可以做一些自救的操作。在远古时
代,处理资源关闭的代码通常写在finally块中。然而,如果你同时打开了多个资源,那么将会出现噩梦般的场景:
public class Demo {
public static void main(String[] args) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bin != null) {
try {
bin.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bout != null) {
try {
bout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
Oh My God!!!关闭资源的代码竟然比业务代码还要多!!!这是因为,我们不仅需要关闭BufferedInputStream,还需要
保证如果关闭BufferedInputStream时出现了异常, BufferedOutputStream也要能被正确地关闭。所以我们不得不借助finally中
嵌套finally大法。可以想到,打开的资源越多,finally中嵌套的将会越深!!!
更为可恶的是,Python程序员面对这个问题,竟然微微一笑很倾城地说:“这个我们一点都不用考虑的嘞~”:
但是兄弟莫慌!我们可以利用Java 1.7中新增的try-with-resource语法糖来打开资源,而无需码农们自己书写资源来关闭代
码。妈妈再也不用担心我把手写断掉了!我们用try-with-resource来改写刚才的例子:
public class TryWithResource {
public static void main(String[] args) {
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
是不是很简单?是不是很刺激?再也不用被Python程序员鄙视了!好了,下面将会详细讲解其实现原理以及内部机制。
评论10