AutoCloseable接口学习

本文介绍Java中资源管理的方式,对比了JDK 1.7前后资源管理的不同,并展示了如何利用try-with-resource语句简化资源的自动关闭过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.test.collection;


public class test3 {

public static void main(String[] args)
{
/*
* jdk1.7之前的try-catch形式
*/
try{
Resource res = new Resource();
ResourceOther resOther = new ResourceOther();
res.doSome();
resOther.doSome();
} catch (Exception ex)  {
ex.printStackTrace();
}finally{
//释放资源
}
System.out.println("--------------------------------------");
/*
  * jdk1.7之后新添加的try-with-resource形式
  * 在try-with-resource中也可以有catch与finally块。
      // 只是catch与finally块是在处理完try-with-resource后才会执行。
       * 可以使用autoCloseable接口自动关闭资源
  */
try(Resource ress=new Resource();ResourceOther resss=new ResourceOther())
{
ress.doSome();
resss.doSome();
}catch(Exception e)
{
e.printStackTrace();
}
}


}


class Resource implements AutoCloseable {
void doSome() {
System.out.println("do something");
}
@Override
public void close() throws Exception {
System.out.println("resource closed");
}
}




class ResourceOther implements AutoCloseable {
void doSome() {
System.out.println("do something other");
}
@Override
public void close() throws Exception {
System.out.println("other resource closed");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值