java7新特性之Try-with-resources statement
try
-with-resources 語句是一個聲明瞭1到多個資源的try語句。資源是指這個try執行完成後必需close掉的物件,比如connection, resultset等。
try
-with-resources 語句會確保在try語句結束時關閉所有資源。實現了java.lang.AutoCloseable
或java.io.Closeable
的物件都可以做為資源。
下面是一個例子,它會從一個檔案中讀出首行文字,這裡使用了BufferedReader
的例項來讀取資料,BufferedReader
是一個資源,它應該在程式完成時被關閉。
-
static String readFirstLineFromFile(String path) throws IOException {
-
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
-
return br.readLine();
-
}
-
}
在這個例子裡面,資源是一個BufferedReader
, 宣告語句是在try後面的括號內。在java7或更晚的版本中,BufferedReader實現了
介面。由於java.lang.AutoCloseable
被定義在BufferedReader
try
-with-resource 語句中,因此不管try程式碼塊是正常完成或是出現異常,這個BufferedReader
在java7之前的版本中,你可以使用finally 程式碼塊來確保資源被關閉(不管try正常完成還是出現異常)。下面是使用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方法都丟擲了異常,readFirstLineFromFileWithFinallyBlock
方法只能丟擲finally程式碼塊裡面的異常,也就是close方法出現的異常,try程式碼塊裡面的異常被禁止;相反,在readFirstLineFromFile
這個例子中,如果try
程式碼塊和try
-with-resources 語句都出現異常,readFirstLineFromFile
方法將出丟擲來自try程式碼塊的異常,從try
-with-resources丟擲的異常被禁止。在java7或更晚的版本中,我們可以獲取到這些被禁止的異常。
你可以宣告1到多個資源,看下面的例子
-
public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
-
throws java.io.IOException {
-
java.nio.charset.Charset charset = java.nio.charset.Charset.forName("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());
-
}
-
}
-
}
在這個例子中,有兩個資源,資源之間用分號隔開。資源被關閉的順序與它們被建立的順序相反,也就是說writer 先被關閉,接著是zf。
下面我們使用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);
-
}
-
}
這裡的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