2016-12-07 41 views
-2

我在這裏有一個示例代碼。函數創建的FileInputStream是否會在代碼存在parentFunction的try/catch塊時自動關閉?函數中的Java AutoClosable行爲

或者是否需要在someOtherFunction()本身中顯式關閉?

private void parentFunction() { 

    try { 
     someOtherFunction(); 
    } catch (Exception ex) { 
    // do something here 

    } 

} 

private void someOtherFunction() { 
    FileInputStream stream = new FileInputStream(currentFile.toFile()); 

    // do something with the stream. 

    // return, without closing the stream here 
    return ; 
} 
+1

你會需要在指定資源['嘗試,用-resources'](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)語句以便它自動關閉 –

回答

0

它需要無論是在someOtherFunction()方法可以顯式關閉,或者在try-與資源塊使用:

private void someOtherFunction() { 
    try (FileInputStream stream = new FileInputStream(currentFile.toFile())) { 

     // do something with the stream. 

    } // the stream is auto-closed 
}