| 
 下面列出了关闭输出流(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  语句.  
 |