Java 函数中的自动关闭行为
Java AutoClosable behaviour in function
我这里有一个示例代码。当代码存在于 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 ;
}
您必须使用带有 try-with-resource 块的资源。
请阅读 AutoCloseable 接口的文档:https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header.
它需要在 someOtherFunction()
方法中显式关闭,或者在 try-with-resources 块中使用:
private void someOtherFunction() {
try (FileInputStream stream = new FileInputStream(currentFile.toFile())) {
// do something with the stream.
} // the stream is auto-closed
}
我这里有一个示例代码。当代码存在于 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 ;
}
您必须使用带有 try-with-resource 块的资源。
请阅读 AutoCloseable 接口的文档:https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header.
它需要在 someOtherFunction()
方法中显式关闭,或者在 try-with-resources 块中使用:
private void someOtherFunction() {
try (FileInputStream stream = new FileInputStream(currentFile.toFile())) {
// do something with the stream.
} // the stream is auto-closed
}