当前位置:   article > 正文

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

java 自动释放连接

程序需要使用各种资源,例如数据库连接,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();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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

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

try-with-resources语句

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

//在try的括号内获取资源
try (FileInputStream fis = new FileInputStream("xxx.txt")){
	//文件读取操作
} catch (Exception e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/590720
推荐阅读
相关标签
  

闽ICP备14008679号