java 资源管理_Java中的自动资源管理

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

资源资源

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

用法

要使用try-with-resources语句,您只需要在括号内声明所需的资源,并且所创建的资源将在代码块末尾自动关闭。以下是try-with-resources语句的语法。

语法try(FileReader fr = new FileReader("file path")) {

//使用资源

} 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值