try-with-resources语句
try-with-resources语句是⼀种声明了⼀种或多种资源的try语句。资源是指在程序⽤完了之后必须要关闭的对象。try-with-resources语句保证了每个声明了的资源在语句结束的时候都会被关闭。任何实现了java.lang.AutoCloseable接⼝的对象,和实现了java.io.Closeable接⼝的对象,都可以当做资源使⽤。
下⾯的例⼦读取了⼀个⽂件的第⼀⾏。它使⽤了⼀个BufferedReader实例去读取⽂件,BufferedReader是⼀种资源,⽤完之后必须关闭。static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
adLine();
}
}
在这个例⼦中,try-with-resources语句种声明的是BufferedReader资源。声明语句紧跟着在try关键词的圆
括号⾥⾯。BufferedReader从Java SE7开始就实现了java.lang.AutoCloseable接⼝。因为BufferedReader声明在了try-with-resources⾥⾯,所以⽆论try语句是正常结束还是异常结束(⽐⽅说adLine⽅法抛出⼀个IOException异常),它都会被关闭。
在Java SE7之前,你可以⽤finally代码块来确保资源⼀定被关闭,⽆论try语句正常结束还是异常结束。下⾯的例⼦⽤finally代码块代替try-with-resources语句:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
adLine();
} finally {
if (br != null) br.close();
java创建文件
}
}
然⽽,在这个例⼦中,如果readLine和close⽅法都抛出异常,那么readFirstLineFromFileWithFinallyBlock⽅法最终会在finally代码块抛出异常,从try代码块⾥⾯抛出的那个异常被抑制住了。相⽐之下,readFirstLineFromFile⽅法中,如果try代码块和try-with-resources语句同时抛出异常,这个⽅法将会最终抛出try代码块⾥⾯的异常,try-with-resources语句⾥⾯抛出的异常被压抑了。在Java SE7之后,你可以回被压抑的异常。参看后⾯的“被压抑的异常”部分。
你可以在⼀个try-with-resources语句⾥⾯声明多个资源。下⾯的例⼦展⽰了从⼀个名字为zipFileName的zip⽂件中检索出⾥⾯所有⽂件的名称,并创建⼀个⽂本⽂件存储所有⽂件名称。
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.(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.wBufferedWriter(outputFilePath, charset)
) {
/
/ Enumerate each entry
for (java.util.Enumeration entries =
// Get the entry name and write it to the output file
String newLine = Property("line.separator");
String zipEntryName =
((java.util.zip.Element()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}
在这个例⼦中,try-with-resources语句包含了两个⽤分号隔开的声明:ZipFile和BufferedWriter。当代码块中代码终⽌,不管是正常还是异常,BufferedWriter和ZipFile对象的close⽅法都会⾃动按声明的相反顺序调⽤。
下⾯的例⼦⽤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 = ateStatement()) {
ResultSet rs = uteQuery(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是JDBC 4.1及其后⾯版本的⼀部分。
注意:try-with-resources语句也可以像普通的try语句⼀样,有catch和finally代码块。在try-with-resources语句中,任何的catch和finally代码块都在所有被声明的资源被关闭后执⾏。
被压抑的异常
try-with-resources语句相关联的代码块可能会抛出异常。在writeToFileZipFileContents例⼦中,try代码块中可能会抛出异常,并且有⾼达两个异常可能会在try-with-resources语句抛出,当试图去关闭ZipFile和BufferedWriter对象的时候。如果在try代码块中抛出⼀个异常,同时在try-with-resources语句中抛出⼀个或多个异常,那么在try-with-resources语句中抛出的异常就被压抑了,并且最终在writeToFileZipFileContents⽅法抛出的异常就是try代码块中抛出的那个异常。你可以通过被try代码块抛出的异常的
实现了AutoCloseable或Closeable接⼝的类
看和接⼝的javadoc,看看实现了它们的类都有哪些。Closeable接⼝继承了AutoCloseable接⼝。不同之处在于,Closeable接⼝的close ⽅法抛出的是IOException异常,AutoCloseable接⼝的close⽅法抛出的是Exception异常。因此,AutoCloseable的⼦类可以重写close⽅法的⾏为,抛出指定的异常,⽐如IOException异常,甚⾄可以不抛出异常。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。