在 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 块中。这只是我想在将资源的所有权转移给另一个对象之前对资源执行一些操作的情况的一个示例。