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方法)。
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方法 处理异常");}}@Overridepublic void close() throws IOException {System.out.println("test2方法这里自动释放资源");}public static void main(String[] args) {test1();test2();}
}
解释:
因为test2中将该类创建对象的过程放置在了try语句中,所以test2会进行自动的资源释放
运行结果:
test1方法 处理逻辑
test1方法 释放资源
test2方法 处理逻辑
test2方法这里自动释放资源