2014-06-23 13 views
17
InputStream in = SomeClass.getInputStream(...); 
BufferedInputStream bis = new BufferedInputStream(in); 

try { 
    // read data from bis 
} finally { 
    bis.close(); 
    in.close();  
} 

Javadoc per BufferedInputStream.close() non menziona se il flusso sottostante è chiuso:Quando chiudo BufferedInputStream, anche l'InputStream sottostante viene chiuso?

chiude questo flusso di input e rilascia le risorse di sistema associate con il flusso. Una volta che lo stream è stato chiuso, ulteriori read(), disponibili(), reset(), o skip() invocherà una IOException. La chiusura di un flusso precedentemente chiuso non ha alcun effetto.

è la chiamata esplicita a in.close() necessario, o dovrebbe essere chiuso dalla chiamata a bis.close()?

+0

Risposta breve: Sì. Risposta lunga: Yeeeeesssss. Seriamente, guarda http://www.docjar.com/html/api/java/io/BufferedInputStream.java.html#472 – Marco13

+2

possibile duplicato di [Closing inputstreams in Java] (http://stackoverflow.com/questions/ 11263926/closing-inputstreams-in-java) –

risposta

21

dal codice sorgente di BufferedInputStream:

public void close() throws IOException { 
    byte[] buffer; 
    while ((buffer = buf) != null) { 
     if (bufUpdater.compareAndSet(this, buffer, null)) { 
      InputStream input = in; 
      in = null; 
      if (input != null) 
       input.close(); 
      return; 
     } 
     // Else retry in case a new buf was CASed in fill() 
    } 
} 

Quindi la risposta sarebbe: SI

4

Quando si chiude un BufferedInputStream, anche l'InputStream sottostante viene chiuso. :)

+0

Potete fornire un riferimento? –

+0

@GrahamBorland si può semplicemente guardare il codice sorgente di Java –

+0

Inoltre, sarebbe la mia lettura di "rilascia qualsiasi risorsa di sistema associata al flusso". Ma sì, potrebbero essere più espliciti. – Thilo

2

Sì. Il flusso sottostante verrà chiuso.

2

Ecco l'implementazione Java

/** 
* Closes this input stream and releases any system resources 
* associated with the stream. 
* Once the stream has been closed, further read(), available(), reset(), 
* or skip() invocations will throw an IOException. 
* Closing a previously closed stream has no effect. 
* 
* @exception IOException if an I/O error occurs. 
*/ 
public void close() throws IOException { 
    byte[] buffer; 
    while ((buffer = buf) != null) { 
     if (bufUpdater.compareAndSet(this, buffer, null)) { 
      InputStream input = in; 
      in = null; 
      if (input != null) 
       input.close(); 
      return; 
     } 
     // Else retry in case a new buf was CASed in fill() 
    } 
} 

Così, il flusso sarà chiusa

4

BufferedInputStream dosent mantiene tutte le risorse del sistema in sé, semplicemente avvolge un InputStream che contiene quelle risorse. Ciò significa che BufferedInputStream non ha nulla da chiudere, quindi inoltra l'operazione di chiusura sull'InputStream spostato che rilascerà le sue risorse.

Problemi correlati