0
点赞
收藏
分享

微信扫一扫

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

whiteMu 2022-02-12 阅读 45

程序需要使用各种资源,例如数据库连接,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();
}
举报

相关推荐

0 条评论