欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java 7的try-with-resources释放资源,,在java7中try后面

来源: javaer 分享于  点击 35198 次 点评:194

java 7的try-with-resources释放资源,,在java7中try后面


在java7中try后面可以跟上资源对象的声明,可以实现在finally中释放资源的功能,如下代码示例:

//try-with-resource statementtry (PrintWriter out2 = new PrintWriter(            new BufferedWriter(            new FileWriter("out.txt", true)))) {    out2.println("the text");} catch (IOException e) {    e.printStackTrace();}

上面的代码实际等同于如下代码:

//close() is in finally clausePrintWriter out = null;try {    out = new PrintWriter(        new BufferedWriter(        new FileWriter("out.txt", true)));    out.println("the text");} catch (IOException e) {    e.printStackTrace();} finally {    if (out != null) {        out.close();    }}

上一个的语法更简洁了一些。

相关栏目:

用户点评