A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lionel 中级黑马   /  2015-1-14 22:17  /  907 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面列出了关闭输出流(output writer) 的三种不同方式.
第一种是将close()方法调用置于try语句块内部;
//close() is in try clause
try {
        PrintWriter out = new PrintWriter(
                        new BufferedWriter(
                        new FileWriter("out.txt", true)));
        out.println("the text");
        out.close();
} catch (IOException e) {
        e.printStackTrace();

}


第二种是将close()方法调用置于finally语句块中;
//close() is in finally clause
PrintWriter 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();
        }

}
第三种是使用从Java 7 开始引进的 try-with-resources 方式;


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

}
哪一种是最好的方式呢?

有一定编程经验的开发者都知道,不论何种情况下(不管有没有异常发生), 输出流都应该被关闭,所以 close()方法应该在 finally块中调用。
但从Java 7 开始,我们也可以使用  try-with-resources  语句.

评分

参与人数 1技术分 +1 收起 理由
lwj123 + 1 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马