国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java 7 try-with-resources自動關閉資源

2019-11-06 07:53:24
字體:
來源:轉載
供稿:網友

java 7開始,提供了一種新的語法try-with-resources用于在資源使用完畢后自動關閉資源,和python中的with語句類似。“資源”指的是實現了java.lang.AutoCloseable的任意對象,因為java.io.CloseableAutoCloseable的子接口,所以實現了Closeable的對象也可以用于該語法。

從文件中讀取第一行,無論try{}中的代碼塊是正常結束還是拋出異常(BufferdReader .readLine throw IOException),BufferdReader都會在使用完后會被自動關閉

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

Java 7之前,可以使用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(); }}

但是finally方式和try-with-resources方式還是有所區別。finally方式中,如果readLine()close()都同時拋出異常,try{}代碼塊中readLine()拋出的異常被捕獲,抑制拋出,而finally{}代碼塊中的close()拋出的異常被向上層調用拋出。try-with-resources對異常抑制的處理和finally相反,如果異常同時在try{}代碼塊和try-with-resources語句中拋出,最后try{}代碼塊中的異常將被拋出,try-with-resources語句中的異常會被抑制,如果需要獲得被抑制的異常,可以通過對拋出的異常調用Throwable.getSupPRessed()提取。

從zip文件中讀取其中的文件名,然后寫入一個文本文件中,通過分號分隔,try-with-resources語句中可以聲明多個資源

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-with-resources語句中聲明的正好相反,上面的例子中,BufferedWriter先關閉,然后ZipFile才關閉。

利用try-with-resources語句自動的關閉java.sql.Statement

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-with-resources可以像傳統的try語句一樣,擁有配套的catch和finally語句塊,需要注意的是任何catch和finally語句塊都在聲明的資源被關閉之后才被運行。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 屏南县| 通海县| 崇仁县| 张家口市| 昌图县| 永登县| 乐安县| 都昌县| 扶余县| 革吉县| 北票市| 高邮市| 什邡市| 怀远县| 增城市| 沭阳县| 龙江县| 天长市| 石首市| 隆昌县| 隆子县| 定边县| 嘉峪关市| 呼伦贝尔市| 河津市| 新河县| 昌都县| 昔阳县| 黔西县| 建湖县| 蒙城县| 临夏市| 寻乌县| 新巴尔虎左旗| 涿州市| 自贡市| 宝山区| 古浪县| 溧水县| 浠水县| 策勒县|