简体   繁体   中英

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.

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.

So is it okay to call br 's close() here, and still can use fis ?

So is it okay to call br's close() here, and still can use 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. It could, for example, pre-buffer some or even all of the fis during construction among many other things.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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