Java 中的 ARM 是什么?
资源是一种实现 AutoClosable 接口的对象。只要在程序中使用了资源,建议在使用后将其关闭。
最初,此任务使用 finally 块完成。
示例
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class FinalExample {
public static void main(String[] args) throws IOException {
File file = null;
FileInputStream inputStream = null;
try {
file = new File("D:\source\sample.txt");
inputStream = new FileInputStream(file);
Scanner sc = new Scanner(inputStream);
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
inputStream.close();
}
}
}输出
This is a sample file with sample text
ARM
Java 中的 ARM 即自动资源管理,它在 Java7 中引入,其中应在 try 块中声明资源,它们将在该块的末尾自动关闭。它也称为 try-with-resources 块,我们在此中声明的对象应为资源,即它们应属于 AutoClosable 类型。
以下是 try-with-resources 语句的语法 −
try(ClassName obj = new ClassName()){
//code……
}从 JSE7 开始引入 try-with-resources 语句。在此中,我们在 try 块中声明一个或多个资源,这些资源将在使用后 (在 try 块末尾) 自动关闭。
我们在 try 块中声明的资源应扩展 java.lang.AutoCloseable 类。
示例
Following program demonstrates the try-with-resources in Java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class FinalExample {
public static void main(String[] args) throws IOException {
try(FileInputStream inputStream = new FileInputStream(new File("D:\source\sample.txt"));) {
Scanner sc = new Scanner(inputStream);
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}输出
This is a sample file with sample text
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!!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP