Java 7 : Try-with-resources – Close resources automatically with AutoCloseable interface

Every time we write code with FileInputStream, BufferReader  etc. we need to close those resource explicitly in finally block.

Now from Java 7, there are two interfaces included Closeable and AutoCloseable with single abstract method close(),  which enables implementing class to close resources aromatically after try block.

Lets see how it works.

Conventional way of using FileInputStream

Now with using Try-with-Resource

How it works:

Compare the changes. Initialization, of resource which needs to be close, happening with try and there is no finally block to close. FileInputStream implements Closeable which have following code in method close().

Note that you can still use finally block if you want.

Closeable vs AutoCloseable

Here is the code


I hope it clears out when to use AutoCloseable and Closeable..

Oracle Page for Try-With-Resources

Leave a Reply

Your email address will not be published. Required fields are marked *