• Post Reply Bookmark Topic Watch Topic
  • New Topic

Closing resources  RSS feed

 
John Smithonian
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

In the line BufferedReader br = new BufferedReader(new Filereader("myFile.txt")), I see two resources, one is br, and one is anonymous.

Now try-with-resources closes br, but what about the anonymous resource? Do inner resources get closed when the outer resource gets closed?

Thanks.
 
Rob Spoor
Sheriff
Posts: 21117
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Smithonian wrote:Do inner resources get closed when the outer resource gets closed?

Although the documentation isn't very clear on it (it just mentions freeing all resources), BufferedReader closes the Reader it wraps. The same goes for BufferedInputStream, FilterReader and FilterInputStream. The matching output classes (BufferedWriter, BufferedOutputStream, FilterWriter and FilterOutputStream) do so as well.
 
Campbell Ritchie
Marshal
Posts: 56209
171
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Find out about try with resources, which is probably the best way to ensure resources are closed.

Never never close anything pointing to System.in or System.out or System.err.
 
John Smithonian
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, thanks guys.
 
Campbell Ritchie
Marshal
Posts: 56209
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Stephan van Hulst
Saloon Keeper
Posts: 7928
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more thing, you technically only need to close inner resources. If you have multiple wrappers around a single resource, you only have to close the inner one:



Be wary that you shouldn't do this with output streams that have cleanup operations (such as flushing a buffer or finishing a compression or encryption algorithm).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!