JDK7 在 Java 异常处理方面引入了哪些变化?
java 8object oriented programmingprogramming更新于 2025/9/22 15:08:17
自 Java 7 以来,引入了 try-with 资源。我们在 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!!

