1. 程式人生 > >Java中IO各種流的先後關閉順序

Java中IO各種流的先後關閉順序

Java中IO各種流的先後關閉順序

2017年06月06日 15:43:49 馬大頭 閱讀數:3858更多

個人分類: I/OJava

還是先看API

 

void close() 
          Closes this stream and releases any system resources associated with it.

 

close

void close
() throws IOException

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.

 

Throws:

IOException - if an I/O error occurs

 

關閉該流並釋放與之關聯的所有資源。在關閉該流後,再呼叫 read()、ready()、mark()、reset() 或 skip() 將丟擲 IOException。關閉以前關閉的流無效。 

[html] view plain copy

  1. public void close() throws IOException {  
  2.     synchronized (lock) {  
  3.         if (in == null)  
  4.         return;  
  5.         in.close();  
  6.         in = null;  
  7.         cb = null;  
  8.     }  
  9. }  

一般情況下是:先開啟的後關閉,後開啟的先關閉

另一種情況:看依賴關係,如果流a依賴流b,應該先關閉流a,再關閉流b

例如處理流a依賴節點流b,應該先關閉處理流a,再關閉節點流b

當然完全可以只關閉處理流,不用關閉節點流。處理流關閉的時候,會呼叫其處理的節點流的關閉方法

如果將節點流關閉以後再關閉處理流,會丟擲IO異常