Java中的自动资源管理


自动资源管理try-with-resources是Java 7中引入的一种新的异常处理机制,它可以自动关闭try-catch块中使用的资源。

资源

资源是指程序完成后需要关闭的对象。例如,读取文件、数据库连接等等。

用法

要使用try-with-resources语句,只需在括号内声明所需的资源,创建的资源将在块结束时自动关闭。以下是try-with-resources语句的语法。

语法

try(FileReader fr = new FileReader("file path")) {    
   // use the resource    
   } catch () {
      // body of catch    
   }
}

以下程序使用try-with-resources语句读取文件中的数据。

示例

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

   public static void main(String args[]) {
      try(FileReader fr = new FileReader("E://file.txt")) {
         char [] a = new char[50];
         fr.read(a);   // reads the contentto the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

旧的资源管理方式

在Java 7之前,当我们使用任何资源(如流、连接等)时,必须使用finally块显式关闭它们。在下面的程序中,我们使用FileReader读取文件中的数据,并使用finally块关闭它。

示例

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

   public static void main(String args[]) {
      FileReader fr = null;        try {
         File file = new File("file.txt");
         fr = new FileReader(file); char [] a = new char[50];
         fr.read(a);   // reads the content to the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         try {
            fr.close();
         } catch (IOException ex) {              ex.printStackTrace();
         }
      }
   }
}

要点

使用try-with-resources语句时,请记住以下几点。

  • 要将类与try-with-resources语句一起使用,它必须实现AutoCloseable接口,并且它的close()方法会在运行时自动调用。

  • 可以在try-with-resources语句中声明多个类。

  • 在try-with-resources语句的try块中声明多个类时,这些类将按相反的顺序关闭。

  • 除了在括号内声明资源外,其他一切都与try块的普通try/catch块相同。

  • 在try块中声明的资源会在try块开始之前实例化。

  • 在try块中声明的资源隐式声明为final。

更新于:2020年6月18日

701 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.