AutoCloseable 接口
概述
AutoCloseable 是从 jdk7 开始存在的接口,位于 java.lang 包中,用于自动执行资源关闭操作。AutoCloseable 接口定义了一个名为 close() 的方法,用于关闭资源。通常在实现 AutoCloseable 接口的类中重写 close() 方法来实现自定义关闭资源的逻辑,例如关闭文件、释放网络连接等。
AutoCloseable 接口是为了配合 Java 7 引入的 try-with-resources(try-catch-finally) 语句而设计的。使用 try-with-resources 语句可以自动关闭实现了 AutoCloseable 接口的资源,无需显式调用 close() 方法,确保资源在使用完毕后被正确关闭,提高代码的可靠性和安全性。
示例
1、在 try-catch-finally 中使用 AutoCloseable 来自动关闭资源:
自定义类实现 AutoCloseable 并重写 close() 方法:
public class StreamExample implements AutoCloseable {
private BufferedReader reader;
public StreamExample(String filePath) throws IOException {
reader = new BufferedReader(new FileReader(filePath));
}
public String readLine() throws IOException {
return reader.readLine();
}
/**
* 重写 close() 方法,自定义关闭资源逻辑
* @throws IOException
*/
@Override
public void close() throws IOException {
reader.close()