有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在使用try with resources,我发现如果我使用out语句,那么我就出了问题

没错

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

不正确的

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

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


共 (2) 个答案

  1. # 1 楼答案

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

    在块之后,在作用域中保留一个资源是没有意义的,因为它已经关闭,您很可能无法使用它(某种“重置”的非承受)

    您还可以在多个块中重复使用相同的变量名,因为它只存在于块的作用域中

    因此,您可以在第一个区块之后再进行一次try (FileWriter fstream = ...)

  2. # 2 楼答案

    有两个原因, 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.