2016-12-07 17 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 
}