Java中使用Closeable接口自動關閉資源詳解
Closeable接口自動關閉資源
Closeable接口繼承于AutoCloseable,主要的作用就是自動的關閉資源,其中close()方法是關閉流并且釋放與其相關的任何方法,如果流已被關閉,那么調用此方法沒有效果,像 InputStream和OutputStream類都實現(xiàn)了該接口,源碼如下
/* * 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.對于實現(xiàn)AutoCloseable接口的類的實例,將其放到try后面(我們稱之為:帶資源的try語句),在try結束的時候,會自動將這些資源關閉(調用close方法)。
test1方法是最常規(guī)的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接口自動關閉資源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java EasyExcel讀寫excel如何解決poi讀取大文件內存溢出問題
這篇文章主要介紹了Java EasyExcel讀寫excel如何解決poi讀取大文件內存溢出問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06spring 整合mybatis后用不上session緩存的原因分析
因為一直用spring整合了mybatis,所以很少用到mybatis的session緩存。什么原因呢?下面小編給大家介紹spring 整合mybatis后用不上session緩存的原因分析,需要的朋友可以參考下2017-02-02Spring的BeanFactoryPostProcessor接口示例代碼詳解
這篇文章主要介紹了Spring的BeanFactoryPostProcessor接口,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02Java利用FileUtils讀取數(shù)據和寫入數(shù)據到文件
這篇文章主要介紹了Java利用FileUtils讀取數(shù)據和寫入數(shù)據到文件,下面文章圍繞FileUtils的相關資料展開怎么讀取數(shù)據和寫入數(shù)據到文件的內容,具有一定的參考價值,徐婭奧德小伙伴可以參考一下2021-12-12深入解析反編譯字節(jié)碼文件中的代碼邏輯JVM中的String操作
這篇文章主要介紹了深入解析反編譯字節(jié)碼文件中的代碼邏輯JVM中的String操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10