java遗珠之try-with-resources

Posted 吴冬冬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java遗珠之try-with-resources相关的知识,希望对你有一定的参考价值。

try-with-resources语句自动关闭实现了AutoCloseable或者 Closeable接口的资源,示例如下:

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

这样会抑制resouce中的异常,如果想看其中发生的异常,还可以增加catch和finally模块,示例如下:

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

但要注意的是,catch和finally都会等到资源关闭之后才执行。

以上是关于java遗珠之try-with-resources的主要内容,如果未能解决你的问题,请参考以下文章

java遗珠之多异常

java遗珠之多异常

java遗珠之重复注解

java遗珠之前言

java遗珠之@SafeVarargs

java遗珠之协变返回类型