Java – Try with resources

From Java7, it introduced the mechanism to release the resource automatically as C# does with using statement. In C#, you can use the using statement to release resource allocated by object which derives from IDisposable.

using (var socket = new Socket(...)) {

}

Java7 can achieve same result with the following syntax. However it cannot use for any object, it can only support the instance which implements java.lang.AutoCloseable as C# does.

try (
    File file = new FileInputStream(...);
    File output = new FileInputStream(...);
) {
}
Advertisements
This entry was posted in Java, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s