Java中AutoCloseable接口与try-with-resources语句自动释放资源

从JDK1.7开始,Java引入了AutoCloseable接口和try-with-resources语句,旨在简化资源管理,避免手动释放导致的错误。当一个对象实现了AutoCloseable接口,它可以在try-with-resources语句中使用,结束后自动调用close方法释放资源,提高了代码的可读性和安全性。例如,FileInputStream作为Closeable接口的实现类,可以配合try-with-resources语句优雅地处理文件输入流的关闭。

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

程序需要使用各种资源,例如数据库连接,IO流,通常做法是在finally代码块中编写释放资源的代码。从JDK1.7以后,提供了自动释放资源的方法

try-catch-finally语句

在finally代码块中释放资源,该操作重复度高,且使代码显得冗长。

FileInputStream fis = null;
try {
    fis = new FileInputStream("xxx.txt");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (fis != null){
        try {
            fis.close(); //释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AutoCloseable接口

AutoCloseable是JDK1.7版本后提供的接口,用于搭配try-with-resources语句自动释放资源,需要资源对象实现该接口,该接口只有一个方法,看看源码注释的第一段就懂了。

/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * 一个对象可能持有一些资源,例如打开的文件或套接字,
 * 直到它被关闭。close()是AutoCloseable的一个方法,
 * 资源对象的close()会被自动调用,前提是该资源对象被声明在
 * try-with-resources语句头部内(即try的括号内)。这一语法结构确保及时
 * 释放资源,避免资源耗尽产生异常和其他可能发生的错误。
 *
 * @author Josh Bloch
 * @since 1.7
 */
public interface AutoCloseable {
    void close() throws Exception;
}

以及它的子接口,IO包下的Closeable接口

public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}
//输入流类实现了该接口,所以可以搭配try-with-resources语句自动释放资源
public abstract class InputStream implements Closeable {}

try-with-resources语句

FileInputStream继承自InputStream,而InputStream实现了Closeable接口,所以可以搭配该语句使用。
在try语句的括号内获取资源,使用完毕后会自动释放,前提是实现了AutoCloseable接口或者Closeable接口,代码简洁了不少。

//在try的括号内获取资源
try (FileInputStream fis = new FileInputStream("xxx.txt")){
	//文件读取操作
} catch (Exception e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值