aspose file tools*
The moose likes Beginning Java and the fly likes Method BufferedReader.close() affect on InputStream? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Method BufferedReader.close() affect on InputStream?" Watch "Method BufferedReader.close() affect on InputStream?" New topic
Author

Method BufferedReader.close() affect on InputStream?

Ivan Franko
Ranch Hand

Joined: May 30, 2011
Posts: 44
For example, I have next method getReader:



and example how I use this method:



In second part of code I use method close() for object reader, but I dont do anything with InputStream in the end. It is ok? Or I must close InputStream too?

Thanks.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14347
    
  22

Calling close() on the BufferedReader will also close the underlying InputStream that the BufferedReader is reading from. You don't need to explicitly close the InputStream yourself.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Ivan Franko
Ranch Hand

Joined: May 30, 2011
Posts: 44
Jesper de Jong, do you know where I can found confirmation in official docs?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
As far as I know, the docs are vague about this. Close() "Closes the stream and releases any system resources associated with it." It's not really clear what "any system resources" means, and it's not clear why they never explicitly name the specific things that do get "released". But in practice, close() on BufferedReader does indeed call close() on the underlying stream. This can be verified by looking at the source code, if you like. The same is true for other similar IO classes that wrap some other underlying stream - OutputStreamWriter, FilterReader, etc. They all close the underlying stream, even though none of them properly document it.
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1510
    
    5

Ivan Franko wrote:Jesper de Jong, do you know where I can found confirmation in official docs?

In the source code of java.io.BufferedReader

Well, I'm not joking - you can actually go and look into source code of those classes - that is far more helpful especially when something is not documented.



I hope this helps.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Stanley Mungai
Ranch Hand

Joined: Dec 09, 2011
Posts: 155

Ivan: I have had a problem of not closing Input streams before. I can tell you that they are safer closed - explicitly.


Give a beggar a fish; feed him for a day. Teach him how to fish; Feed him for a lifetime.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method BufferedReader.close() affect on InputStream?