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 i编程编程客栈s 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 Cl编程客栈oseableTest 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 (Clos编程eableTest 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接口自动关闭资源内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论