有3個接口對於流類相當重要。其中兩個接口是Closeable和Flushable,它們是在java.io包中定義的,並且是由JDK5添加的。第3個接口是AutoColseable,它是由JDK7添加的新接口,被打包到java.lang包中。
AutoCloseable接口對JDK7新添加的帶資源的try語句提供了支持,這種try語句可以自動執行資源關閉過程。只有實現了AutoCloseable接口的類的對象才可以由帶資源的try語句進行管理。AutoCloseable接口只定義了close()方法:
1
|
void
close()
throws
Exception
|
這個方法關閉調用對象,釋放可能占用的所有資源。在帶資源的try語句的末尾,會自動調用該方法,因此消除了顯式調用close()方法的需要。
Closeable接口也定義了close()方法。實現了Closeable接口的類的對象可以被關閉。從JDK7開始,Closeable擴展了AutoCloseable。因此,在JDK7中,所有實現了Closeable接口的類也都實現了AutoCloseable接口。
實現了Flushable接口的類的對象,可以強制將緩存的輸出寫入到與對象關聯的流中。該接口定義了flush()方法,如下所示:
1
|
void
flush()
throws
IOException
|
刷新流通常會導致緩存的輸出被物理地寫入到底層設備中。寫入流的所有I/O類都實現了Flushable接口。
注:關於帶資源的try語句的3個關鍵點:
-
由帶資源的try語句管理的資源必須是實現了AutoCloseable接口的類的對象。
-
在try代碼中聲明的資源被隱式聲明為fianl。
-
通過使用分號分隔每個聲明可以管理多個資源。
此外請記住,所聲明資源的作用域被限制在帶資源的try語句中。帶資源的try語句的主要優點是:當try代碼塊結束時,資源(在此時流)會被自動關閉。因此,不太可能會忘記關閉流。使有帶資源的try語句,通常可以使源代碼更短,更清晰,更容易維護。如例:
package demo; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; /** * AutoCloseable接口,表示一種不再使用時需要關閉的資源。這個接口下只有一個方法,close()。這個方法在try-with- * resource語法下會被自動調用,支持拋出Exception,當然它也鼓勵拋出更詳細的異常。close()建議不要拋出線程中斷的 * InterruptedException。對這個接口的實現,規范強烈建議close()是冪等的,也就是說多次調用close()方法和一次調用的結 * 果是一樣的。 * JDK1.7 新特性 * */ public class InputStreamReaderTest { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("src\\fuhd.txt"), "UTF8"), 1024)) { System.out.println(reader.readLine()); } catch (Exception e) { e.printStackTrace(); } //示例,聲明自己的兩個資源類,實現AutoCloseable接口。 try (MyResource myResource = new MyResource(); MyResource2 myResource2 = new MyResource2()) { myResource.readResource(); myResource2.readResource(); } catch (Exception e) { e.printStackTrace(); } } } class MyResource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("close resource"); } public void readResource() { System.out.println("read resource"); } } class MyResource2 implements AutoCloseable { @Override public void close() throws Exception { System.out.println("close resource2"); } public void readResource() { System.out.println("read resource2"); } }
輸出
熱度...........................。
read resource
read resource2
close resource2
close resource