简体   繁体   English

在Java中关闭最外层的流对象

[英]Closing an outermost stream object in Java

When I write something like this: 当我写这样的东西:

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\test.txt")));
br.close();

closing the outermost object, in this case br , will automatically close all the chained objects too. 关闭最外面的对象(在这种情况下为br )也会自动关闭所有链接的对象。

But what if there's still a reference to a chained object? 但是,如果仍然有对链接对象的引用呢?

Something like this: 像这样:

FileInputStream fis = new FileInputStream("c:\\test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
br.close();

In this case, I don't want fis to be released, because I need to use it in the other stream soon. 在这种情况下,我不希望释放fis ,因为我需要尽快在其他流中使用它。

So is it okay to call br 's close() here, and still can use fis ? 因此,可以在此处调用brclose() ,并且仍然可以使用fis吗?

So is it okay to call br's close() here, and still can use fis? 因此,可以在这里调用br的close(),并且仍然可以使用fis吗?

No! 没有!

Once br has wrapped fis , fis should not be used for any other purpose because br has made the assumption that fis is for it and it alone to do with it what it wishes. 一旦br包裹了fis ,就不应将fis用作任何其他用途,因为br假设fis是为它而做的,并且仅凭它来完成它所希望的事情。 It could, for example, pre-buffer some or even all of the fis during construction among many other things. 例如,它可以在构造过程中预先缓冲某些甚至全部fis

Using fis for anything other than what br uses it for will not only give unpredictable results but it will most likely interfere with br 's functionality significantly. fis用作br用途之外的其他任何东西,不仅会产生不可预测的结果,而且很可能会严重干扰br的功能。

Even if all you do is close br immediately after creating it it is quite reasonable for fis to then be at least part-consumed if not completely consumed - it is also supposed to be closed. 即使你做的是密切br创建后立即那是相当合理的fis然后被至少部分消耗如果没有完全消耗掉-它也应该被关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM