在 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