Java中使用Closeable接口自动关闭资源详解
Closeable接口自动关闭资源
Closeable接口继承于AutoCloseable,主要的作用就是自动的关闭资源,其中close()方法是关闭流并且释放与其相关的任何方法,如果流已被关闭,那么调用此方法没有效果,像 InputStream和OutputStream类都实现了该接口,源码如下
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.io;
import java.io.IOException;
/**
* A {@code Closeable} is a source or destination of data that can be closed.
* The close method is invoked to release resources that the object is
* holding (such as open files).
*
* @since 1.5
*/
public interface Closeable extends AutoCloseable {
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
* <p> As noted in {@link AutoCloseable#close()}, cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* <em>mark</em> the {@code Closeable} as closed, prior to throwing
* the {@code IOException}.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
}Closeable用法
1.在1.7之前,我们通过try{} finally{} 在finally中释放资源。
2.对于实现AutoCloseable接口的类的实例,将其放到try后面(我们称之为:带资源的try语句),在try结束的时候,会自动将这些资源关闭(调用close方法)。
test1方法是最常规的try{}catch{}finally{}
test2是使用closeable自动释放资源
package com.canal.demo;
import java.io.Closeable;
import java.io.IOException;
public class CloseableTest implements Closeable {
public static void test1() {
try {
System.out.println("test1方法 处理逻辑");
} catch (Exception e) {
System.out.println("test1方法 异常处理");
} finally {
System.out.println("test1方法 释放资源");
}
}
public static void test2() {
try (CloseableTest c = new CloseableTest()) {
System.out.println("test2方法 处理逻辑");
} catch (Exception e) {
System.out.println("test2方法 处理异常");
}
}
@Override
public void close() throws IOException {
System.out.println("test2方法这里自动释放资源");
}
public static void main(String[] args) {
test1();
test2();
}
}运行结果如下

到此这篇关于Java中使用Closeable接口自动关闭资源详解的文章就介绍到这了,更多相关Closeable接口自动关闭资源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Springboot以Repository方式整合Redis的方法
这篇文章主要介绍了Springboot以Repository方式整合Redis的方法,本文通过图文并茂实例详解给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-04-04
Java参数校验详解之使用@Valid注解和自定义注解进行参数验证
在后端开发中,参数校验是非常普遍的,下面这篇文章主要给大家介绍了关于Java参数校验详解之使用@Valid注解和自定义注解进行参数验证的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下2024-06-06
一文详解Spring中的HttpMessageNotReadableException异常处理
这篇文章主要为大家详细介绍了Spring中的HttpMessageNotReadableException异常,分析其产生的原因并通过实际代码示例展示如何有效地捕获和处理这一异常,感兴趣的可以了解下2025-02-02
mybatis中orderBy(排序字段)和sort(排序方式)引起的bug及解决
这篇文章主要介绍了mybatis中orderBy(排序字段)和sort(排序方式)引起的bug,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01


最新评论