java7新特性之Try-with-resources statement

try-with-resources 语句是一个声明了1到多个资源的try语句。资源是指这个try执行完成后必需close掉的对象,比如connection, resultset等。

try-with-resources 语句会确保在try语句结束时关闭所有资源。实现了java.lang.AutoCloseablejava.io.Closeable的对象都可以做为资源。

下面是一个例子,它会从一个文件中读出首行文本,这里使用了BufferedReader 的实例来读取数据,BufferedReader是一个资源,它应该在程序完成时被关闭。

 
  1. static String readFirstLineFromFile(String path) throws IOException {

  2. try (BufferedReader br = new BufferedReader(new FileReader(path))) {

  3. return br.readLine();

  4. }

  5. }

在这个例子里面,资源是一个BufferedReader, 声明语句是在try后面的括号内。在java7或更晚的版本中,BufferedReader实现了java.lang.AutoCloseable接口。由于BufferedReader被定义在try-with-resource 语句中,因此不管try代码块是正常完成或是出现异常,这个BufferedReader 的实例都将被关闭。

在java7之前的版本中,你可以使用finally 代码块来确保资源被关闭(不管try正常完成还是出现异常)。下面是使用finally的例子:

 
  1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {

  2. BufferedReader br = new BufferedReader(new FileReader(path));

  3. try {

  4. return br.readLine();

  5. } finally {

  6. if (br != null) br.close();

  7. }

  8. }

然而,在这里例子里面,如果readLine方法和close方法都抛出了异常,readFirstLineFromFileWithFinallyBlock 方法只能抛出finally代码块里面的异常,也就是close方法出现的异常,try代码块里面的异常被禁止;相反,在readFirstLineFromFile这个例子中,如果try 代码块和try-with-resources 语句都出现异常,readFirstLineFromFile 方法将出抛出来自try代码块的异常,从try-with-resources抛出的异常被禁止。在java7或更晚的版本中,我们可以获取到这些被禁止的异常。

你可以声明1到多个资源,看下面的例子

 
  1. public static void writeToFileZipFileContents(String zipFileName, String outputFileName)

  2. throws java.io.IOException {

  3.  
  4. java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");

  5. java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

  6.  
  7. // Open zip file and create output file with try-with-resources statement

  8.  
  9. try (

  10. java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);

  11. java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)

  12. ) {

  13.  
  14. // Enumerate each entry

  15.  
  16. for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

  17.  
  18. // Get the entry name and write it to the output file

  19.  
  20. String newLine = System.getProperty("line.separator");

  21. String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;

  22. writer.write(zipEntryName, 0, zipEntryName.length());

  23. }

  24. }

  25. }


 

在这个例子中,有两个资源,资源之间用分号隔开。资源被关闭的顺序与它们被创建的顺序相反,也就是说writer 先被关闭,接着是zf。

 下面我们使用try-with-resources 语句自动关闭一个java.sql.Statement 对象:

 
  1. public static void viewTable(Connection con) throws SQLException {

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

  4.  
  5. try (Statement stmt = con.createStatement()) {

  6.  
  7. ResultSet rs = stmt.executeQuery(query);

  8.  
  9. while (rs.next()) {

  10. String coffeeName = rs.getString("COF_NAME");

  11. int supplierID = rs.getInt("SUP_ID");

  12. float price = rs.getFloat("PRICE");

  13. int sales = rs.getInt("SALES");

  14. int total = rs.getInt("TOTAL");

  15. System.out.println(coffeeName + ", " + supplierID + ", " + price +

  16. ", " + sales + ", " + total);

  17. }

  18.  
  19. } catch (SQLException e) {

  20. JDBCTutorialUtilities.printSQLException(e);

  21. }

  22. }


这里的java.sql.Statement 是JDBC4.1或更晚的API的一部分。

注意:try-with-resources 也可以有catch和finally语句块,就像使用一个普通的try语句一样。在try-with-resources 语句中,catch或者finally将在资源被关闭后执行。

from:https://blog.csdn.net/fireofjava/article/details/7220754 

猜你喜欢

转载自blog.csdn.net/GarfieldEr007/article/details/85642928