The following are 3 different ways to close a output writer. The first one puts close() method in try clause, the second one puts close in finally clause, and the third one uses a try-with-resources statement. Which one is the right or the best?

//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() 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();
}
}
//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();
}

Answer

Because the Writer should be closed in either case (exception or no exception), close() should be put in finally clause.

From Java 7, we can use try-with-resources statement.Why?

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path)))
{
return br.readLine();
}
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The classBufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because theBufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLinethrowing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether thetry statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}

However, in this example, if the methods readLine and close both throw exceptions, then the methodreadFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the methodreadFirstLineFromFile throws the exception thrown from the try block; the exception thrown from thetry-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

public static void writeToFileZipFileContents(String zipFileName,
String outputFileName)
throws java.io.IOException { java.nio.charset.Charset charset =
java.nio.charset.StandardCharsets.US_ASCII;
java.nio.file.Path outputFilePath =
java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with
// try-with-resources statement try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
{
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon:ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try-with-resources statement to automatically close a java.sql.Statementobject:

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query); while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " +
price + ", " + sales + ", " + total);
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
}

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile andBufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by thewriteToFileZipFileContents method. You can retrieve these suppressed exceptions by calling theThrowable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of theCloseable interface throws exceptions of type IOException while the close method of the AutoCloseableinterface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

最新文章

  1. CRL快速开发框架系列教程九(导入/导出数据)
  2. java 内存机制
  3. QT自定义精美换肤界面
  4. 《构建之法》第8、9、10章读后感和Sprint总结
  5. React组件测试(模拟组件、函数和事件)
  6. 深入理解计算机系统第二版习题解答CSAPP 2.14
  7. 第 7 章 MySQL 数据库锁定机制
  8. Python使用虚拟环境
  9. Thinkphp 3.2中文章详情页的上一篇 下一篇文章功能
  10. bootstrap 选项卡的使用
  11. 论python中的函数参数的传递问题。
  12. recyclerview 主活动里监听点击事件
  13. 安装Java8以后,Eclipse运行异常解决方案
  14. python csv读写
  15. 详解Transformer模型(Atention is all you need)
  16. 一劳永逸:域名支持通配符,ASP.NET Core中配置CORS
  17. request 模块详细介绍
  18. socket套接字和驱动绑定分析
  19. ImageCollection
  20. 多线程并发容器CopyOnWriteArrayList

热门文章

  1. 使用Zabbix监控RabbitMQ
  2. SDUT 2772 数据结构实验之串一:KMP简单应用
  3. CentOS安装 Docker
  4. 委托delegate使用方法
  5. curl 取不到第二个参数解决方法
  6. poj1840 哈希
  7. 线性回归的Spark实现 [Linear Regression / Machine Learning / Spark]
  8. (转载)Android content provider基础与使用
  9. Ajax清除浏览器js、css、图片缓存的方法
  10. Ajax的利弊