我这里有一个示例代码。将函数创建的FileInputStream会在代码存在于parentFunction的try / catch块时自动关闭吗?
或者它是否需要在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 ;
}
答案 0 :(得分:0)
您必须将资源与try-with-resource块一起使用。
请阅读AutoCloseable界面的文档:https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
退出在资源规范头中已声明对象的try-with-resources块时,将自动调用AutoCloseable对象的方法。
答案 1 :(得分: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
}