为什么在 Try with resource 中使用全局资源时不正确

why not correct when using global resource in Try with resource

我正在对资源使用 try,我发现如果我使用 out 语句,就会出错

正确一个,

try (FileWriter fstream = new FileWriter(mergedFile, true);) {
 }

一个不正确

FileWriter fstream = null;
try (fstream = new FileWriter(mergedFile, true);) {
}

我想知道为什么我不能使用第二个? with资源的范围不同?

是的,这是正确的,因为使用 try with resources 声明的资源在块的末尾是 closed,它不是在该块的范围之外可用。

在块之后范围内保留资源是没有意义的,因为它已经关闭并且您很可能无法使用它(某种"reset" 无视)。

您还可以在多个块中重复使用相同的变量名称,因为它只存在于块的范围内。

所以你可以在你的第一个区块之后跟进另一个 try (FileWriter fstream = ...)

有两个原因, 1.资源必须是最终的。在执行 try-with-resources 块期间,可以随时更改外部声明的变量。这会破坏它的清理并使其不一致。

  1. 资源作用域必须是与其关联的 try 块。

以下是 Java 7 规范文档中的确切词句,

A ResourceSpecification declares one or more local variables with initializer expressions to act as resources for the try statement.

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.

同样来自规范的 6.3

The scope of a variable declared in the ResourceSpecification of a try-with-resources statement (§14.20.3) is from the declaration rightward over the remainder of the ResourceSpecification and the entire try block associated with the try-with-resources statement.