• Post Reply Bookmark Topic Watch Topic
  • New Topic

try with resource  RSS feed

 
Linwood Hayes
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we do


When try block finishes, does it automatically close "InputStream is" or "myResource" ?  or close both of them ?


Thanks.
 
Dave Tolls
Ranch Foreman
Posts: 3056
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It closes the InputStream, so is.
Try-with-resources closes any variables that are declared and initialised in that block.
 
O Shea
Ranch Hand
Posts: 196
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya and the resource which you are using should be of Auto-Closable type.
Reference->Here
 
Quintin Stephenson
Ranch Hand
Posts: 44
1
Java Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Linwood

If your try with resource example was


Then your resource is InputStream is will close at the end of the try block because it has the Closable and AutoCloseable interfaces.

However in your example you have not stated what "myResource" is.  Is it a class, or and instance of a class.  Does the getInputStream method return a new InputStream everytime or merely return an existing InputStream instance that resides in a the class.  If it is the latter the InputStream in the myResource class instance (of where ever it came from) will also be closed at the end of the try with resource block because they are the same instance.

hope that helps
Q
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!