Java中的自动资源管理(尝试使用资源语句)
Java提供了使代码更健壮并减少代码行数的功能。从Java 7 开始,此功能称为使用try-with-resources的自动资源管理 (ARM)。 try-with-resources 语句是声明一个或多个资源的 try 语句。
此语句确保在语句末尾关闭每个资源,这简化了在出现错误或成功完成代码块时需要处置或关闭的外部资源的工作。
什么是资源?
资源是程序使用完后必须关闭的对象。任何实现Java.lang.AutoCloseable的对象,包括所有实现Java.io.Closeable 的对象,都可以用作资源。
一种旧的资源清理方法——使用 finally
在 JDK 1.7 之前的早期Java版本中,资源的关闭是使用 finally 块完成的。
Java
// Java program to illustrate cleaning of
// resources before Java 7
import java.io.*;
import java.util.*;
import java.io.*;
class Resource
{
public static void main(String args[])
{
BufferedReader br = null;
String str = " ";
System.out.println("Enter the file path");
br = new BufferedReader(new InputStreamReader(System.in));
try
{
str = br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
String s;
// file resource
br = new BufferedReader(new FileReader(str));
while ((s = br.readLine()) != null)
{
// print all the lines in the text file
System.out.println(s);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
// closing the resource in 'finally' block
br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
Java
// Java program to illustrate
// Automatic Resource Management
// in Java without finally block
import java.io.*;
import java.util.*;
class Resource {
public static void main(String args[])
{
String str = "";
BufferedReader br = null;
System.out.println("Enter the file path");
br = new BufferedReader(
new InputStreamReader(System.in));
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
// try with Resource
// note the syntax difference
try (BufferedReader b
= new BufferedReader(new FileReader(str))) {
String s;
while ((s = b.readLine()) != null) {
System.out.println(s);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Java
// Java program to illustrate
// Automatic Resource Management
// in Java with multiple resource
class Resource {
public static void main(String s[])
{
// note the order of opening the resources
try (Demo d = new Demo(); Demo1 d1 = new Demo1()) {
int x = 10 / 0;
d.show();
d1.show1();
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
}
// custom resource 1
class Demo implements AutoCloseable {
void show() { System.out.println("inside show"); }
public void close()
{
System.out.println("close from demo");
}
}
// custom resource 2
class Demo1 implements AutoCloseable {
void show1() { System.out.println("inside show1"); }
public void close()
{
System.out.println("close from demo1");
}
}
输出:
hello
java
新方法——使用 try-with-resources
在 try-with-resources 方法中,没有使用 finally 块。文件资源在小括号内的 try 块中打开。只有那些类的对象才能在实现 AutoCloseable 接口的块内打开,并且这些对象也应该是本地的。无论 try 语句是正常完成还是突然完成,资源都会自动关闭。
句法:
以下示例从文件中读取第一行。它使用 BufferedReader 的实例从文件中读取数据。 BufferedReader 是程序完成后必须关闭的资源:
static String readFirstLineFromFile(String path) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}
}
Java
// Java program to illustrate
// Automatic Resource Management
// in Java without finally block
import java.io.*;
import java.util.*;
class Resource {
public static void main(String args[])
{
String str = "";
BufferedReader br = null;
System.out.println("Enter the file path");
br = new BufferedReader(
new InputStreamReader(System.in));
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
// try with Resource
// note the syntax difference
try (BufferedReader b
= new BufferedReader(new FileReader(str))) {
String s;
while ((s = b.readLine()) != null) {
System.out.println(s);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
hello
java
多个资源中的自动资源管理
多个资源可以在 try-with-resources 块中使用,并自动关闭它们。在这种情况下,资源将按照它们在括号内创建的相反顺序关闭。
Java
// Java program to illustrate
// Automatic Resource Management
// in Java with multiple resource
class Resource {
public static void main(String s[])
{
// note the order of opening the resources
try (Demo d = new Demo(); Demo1 d1 = new Demo1()) {
int x = 10 / 0;
d.show();
d1.show1();
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
}
// custom resource 1
class Demo implements AutoCloseable {
void show() { System.out.println("inside show"); }
public void close()
{
System.out.println("close from demo");
}
}
// custom resource 2
class Demo1 implements AutoCloseable {
void show1() { System.out.println("inside show1"); }
public void close()
{
System.out.println("close from demo1");
}
}
输出:
close from demo1
close from demo
Note: In the above example, Demo and Demo1 are the custom resources managed inside the try block. Such resources need to implement the AutoCloseable interface. When we open any such AutoCloseable resource in the special try-with-resource block, immediately after finishing the try block, JVM calls this.close() method on all resources initialized in the try block.
要点:
- finally 块用于在Java 7 之前清理资源。
- 在Java 7 之后,资源清理会自动完成。
- 由于接口 AutoCloseable,当您在 try-with-resources 块中初始化资源时,ARM 就完成了。一旦 try 块完成,JVM 就会调用它的 close 方法。
- 调用 close() 方法可能会导致意外结果。
- 我们在 try-with-resource 中使用的资源必须是 AutoCloseable 的子类型,以避免编译时错误。
- 多资源 ARM 中使用的资源必须按照上例中给出的相反顺序关闭