在Java7中,有一种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块中。这只是我想要在将资源的所有权转移到另一个对象之前对该资源执行某些操作的一个例子。
发布于 2014-05-31 05:58:46
try-with旨在用于这样一种情况:所标识的资源永远不能在try块的作用域之外持久存在。
如果要使用try-with结构,则必须按如下方式更改设计:
openTwoFiles()方法。DualInputStream类创建一个构造函数,该构造函数接受两个文件名并创建两个InputStreams。声明此构造函数抛出IOException,并允许它在try-with构造中抛出IOExceptions.https://stackoverflow.com/questions/23963829
复制相似问题