Closeable类出了那么久我才知道还能这么用。

	由于使用到ElasticSearch,很多jar包都是大佬封装好给我们直接使用的,所以不得不开始探寻jar的源码,
从中也学会了一些骚操作。

这是我公司封装的一个连接操作ElasticSearch的client类,可以看到其接口继承了一个Closeable接口。

public interface EsClient extends Closeable
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;
}

其意思很明确,就是关闭stream和资源的一个方法。我们打开InputStream也可以看到其继承了这个接口。我们平常使用完流以后都会close,关闭资源占用。

在java1.7以后其实try-catch有了一个骚操作,我们可以将需要关闭的流资源等,放在try(括号里边)。
例:

import java.io.IOException;
import java.io.InputStream;

public class TestTry {
    public static void main(String[] args) {
        try(
                InputStream inputStream = new MyInputStream();
        ) {
            System.out.println("执行体");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static class MyInputStream extends InputStream{

        @Override
        public int read() throws IOException {
            return 0;
        }

        @Override
        public void close() throws IOException {
            System.out.println("执行了关闭");
            super.close();
        }
    }
}

执行结果:

执行体
执行了关闭

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值