这个问题分为两部分:
InputStream i1 = new InputStream()
和 和有什么不一样new InputStream()
?创建所有局部变量只是为了关闭它们是否值得
?
我知道第一个简单的答案,你可以保留变量,继续使用变量,甚至像一个优秀的程序员一样关闭输入流。第二个你失去了它的参考,但它看起来更简洁。两者之间有内存差异吗?速度差异(破坏)怎么样?
现在来看那些激发我思考的例子。首先我们使用 `'new Object()` 不考虑扔掉它。
public void getLongStrings() throws IOException {
try {
foo = FileCopyUtils.copyToString(new InputStreamReader(aBook.getInputStream()));
bar = FileCopyUtils.copyToString(new InputStreamReader(aNovel.getInputStream()));
}
catch (IOException ioe) {
//do something appropriate here;
}
}
现在是更详细的方法
public void getLongStrings() throws IOException {
InputStream i1 = null;
InputStream i2 = null;
InputStreamReader isr1 = null;
InputStreamReader isr2 = null;
try {
i1 = aBook.getInputStream();
i2 = aNovel.getInputStream();
isr1 = new InputStreamReader(i1);
isr2 = new InputStreamReader(i2);
foo = FileCopyUtils.copyToString(isr1);
bar = FileCopyUtils.copyToString(isr2);
}
catch (IOException ioe) {
//do something appropriate here
} finally {
if (i1 != null) i1.close();
if (i2 != null) i2.close();
if (isr1 != null) isr1.close();
if (isr2 != null) isr2.close();
}
}
第一个好还是第二个好?一个比另一个快吗?即使看起来不漂亮,关闭所有流是否明智?
感谢您提供任何见解(或编辑)。