2

在 Java 7 中,有一种 try-with 语法可确保像 InputStream 这样的对象在所有代码路径中都关闭,而不管异常如何。但是,在 try-with 块中声明的变量(“is”)是最终的。

try (InputStream is = new FileInputStream("1.txt")) {
    // do some stuff with "is"
    is.read();

    // give "is" to another owner
    someObject.setStream(is);

    // release "is" from ownership: doesn't work because it is final
    is = null;
}

在 Java 中是否有简洁的语法来表达这一点?考虑这种异常不安全的方法。添加相关的 try/catch/finally 块将使该方法更加冗长。

InputStream openTwoFiles(String first, String second)
{
    InputStream is1 = new FileInputStream("1.txt");

    // is1 is leaked on exception
    InputStream is2 = new FileInputStream("2.txt");

    // can't use try-with because it would close is1 and is2
    InputStream dual = new DualInputStream(is1, is2);
    return dual;
}

显然,我可以让调用者打开这两个文件,将它们都放在一个 try-with 块中。这只是我想在将资源的所有权转移给另一个对象之前对资源执行一些操作的情况的一个示例。

4

1 回答 1

1

try-with 旨在用于已识别资源绝不能持续存在于 try 块范围之外的情况。

如果你想使用 try-with 结构,你必须改变你的设计如下:

  1. 删除openTwoFiles()方法。它是无价值的。
  2. DualInputStream为接受两个文件名的类创建一个构造函数并创建两个InputStreams. 声明此构造函数 throwsIOException并允许它 throw IOExceptions
  3. 在 try-with 构造中使用新的构造函数。
于 2014-05-30T21:58:46.073 回答