-2

我这里有一个示例代码。当代码存在 parentFunction 的 try/catch 块时,函数创建的 FileInputStream 会自动关闭吗?

还是需要在 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 ;
}
4

2 回答 2

0

您必须将资源与 try-with-resource 块一起使用。

请阅读 AutoCloseable 接口的文档:https ://docs.oracle.com/javase/8/docs/api/java/lang/Au​​toCloseable.html

AutoCloseable 对象的方法在退出资源规范标头中已为其声明对象的 try-with-resources 块时自动调用。

于 2016-12-07T21:20:42.667 回答
0

它需要在someOtherFunction()方法中显式关闭,或者在 try-with-resources 块中使用:

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

        // do something with the stream.

    } // the stream is auto-closed
}
于 2016-12-07T21:21:56.417 回答