Java之Java7新特性之try资源句式

Java之Java7新特性之try资源句式

一、【try资源句式】是干嘛用的?

在JDK 7版本中出现了一种新的句式: try(资源)

任何实现了 java.lang.AutoCloseable 接口的类

都可以使用 try资源句式,自动 close。

public interface java.io.Closeable extends java.lang.AutoCloseable  

一句话:
使用 try资源句式 用来自动 close 资源。而不用担心资源一直占用内存无法释放。

二、使用语法 - 何时自动关闭资源

下面的例子用于读取文件的第一行。它使用一个 BufferedReader 的实例来读取数据。
BufferedReader 在这里就是一个资源,它必须在程序运行结束后被关闭。

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

BufferedReader 在 jdk1.7 中实现了 java.lang.AutoCloseable 接口,
它将被自动关闭,无论是程序正常结束还是中途抛出异常。

三、异常是如何被抛出/捕获的?

try资源句式 其功能是用于资源的自动关闭,而对于异常的 catch 和 finally,
在写法上跟 jkd 1.7 之前没有区别。

在 jdk 1.7 之前,如果遇到异常,会写在 catch 中,然后在 finally 块中关闭资源。

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

上例中如果 readLine() 和 close() 都抛出异常时,该方法抛出的异常是 finally 块中的异常,
try块中的异常被忽略了。

与之相反的是,try资源句式 则会抛出try块中的异常,try句式中的异常被忽略掉了。
当然你仍然可以在 catch() 块中获取到被忽略的异常。

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

四、可以 try 多个资源

使用 try资源句式 时,可以将多个资源写在一起,中间用分号隔开。
注意:
1、最后一个资源后面没有分号。
2、资源的关闭顺序跟写的顺序相反(最先打开的最后关闭)。

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

五、获取被 try资源句式 忽略的异常

前述已讲过,try{} 体中的异常会覆盖掉 try() 表达式中的异常。
但仍然可以通过 try{} 体中抛出的异常 和 Throwable.getSuppressed() 方法获取那些被忽略的异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值