在 JDK 7 中引入了哪些與 Java 中異常處理相關的新特性?
自 Java 7 起引入了 try-with-resources。這樣,我們就可以在 try 塊中宣告一個或多個資源,並在使用後自動關閉它們(在 try 塊的末尾)。
我們在 try 塊中宣告的資源應擴充套件 java.lang.AutoCloseable 類。
示例
以下程式演示了 Java 中的 try-with-resources。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopying {
public static void main(String[] args) {
try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt"));
FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){
byte[] buffer = new byte[1024];
int length;
while ((length = inS.read(buffer)) > 0) {
outS.write(buffer, 0, length);
}
System.out.println("File copied successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}輸出
File copied successfully!!
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP