Java 7 – try-with-resources Statement

Java 7 provides a new approach for closing resources with clean & clear code by try-with-resources statment. In the article, JavaSampleApproach will introduce the benifit when programming by try-with-resources statement.

Related Post: Understand Java Exception & The effect to Java Program (Single & Multi Thread)

I. Concepts

What is a resource? An object that implements java.lang.AutoCloseable or java.io.Closeable is called a resource.
Some Java resource classes:
– java.io.BufferedReader.BufferedReader
– java.net.Socket.Socket
– java.sql.Statement

try-with-resources statement ensures that each resource is closed after completed execution of the statement.

II. Practice

For see benifits of try-with-resources statement, JavaSampleApproach makes an sample with BufferedReader for reading a text file.

1. Use Java6 or early version and Problems

– After reading a file, we take a risk if developers do Not remember to close resources.

– Source code is not clear & clean:

So how to improve it?

2. Java 7 – New Approach by try-with-resources statement

By try-with-resources statement, our code is clear and clean. Developers do NOT need to close the resources so one risk is auto removed.

That is better? Right!

IV. Source code

Java7TryWithResource


Related Posts



Got Something To Say:

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

*