Java Example: Try-with-resources Statement

Java

Beginning with Java 7, a new feature called try-with-resources statement has been introduced to improve the resource management and exception handling code.

All the resources that declared in the try-with-resources statement will be closed automatically when the try block exits. The resource can be a file, database connection, network connection or any object that implements java.lang.AutoCloseable or java.io.Closeable.

In this tutorial, we’ll show you some examples of how to manage the resources in Java 6 and Java 7.

What You’ll Need

Syntax

This is the syntax of try-with-resources statement in Java 7 or above.

Try (Open Resource 1; Open Resource 2; ...) {

    // Use the opened Resource 1, Resource 2, ...

} catch (Exception) {

    // Handle exception (Optional)

}
Note:

  • The opened resources will be closed automatically when exit the try block.
  • The catch and finally blocks are optional in try-with-resources statement.

Java 6 Example

In Java 6 and before, we have to manage the resources using try-catch-finally block.

C:\test1.txt

This is file test1.txt
This is Java 6 resource management example

Java6ResourceManagementExample.java

package com.chankok.io;

import java.io.FileReader;
import java.io.IOException;

public class Java6ResourceManagementExample {

    public static void main(String[] args) {

        FileReader fr = null;

        try {
            // Create an input stream
            fr = new FileReader("C:\\test1.txt");

            int data;
            // Read a character and print it on console one by one
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the input stream
                if (fr != null) fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

Output:

This is file test1.txt
This is Java 6 resource management example

Java 7 Example – Manage Single Resource

In this example, we manage single resource using try-with-resources statement.

C:\test2.txt

This is file test2.txt
This is Java 7 example - Manage single resource with try-with-resources

TryWithResourcesSingleResourceExample.java

package com.chankok.io;

import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesSingleResourceExample {

    public static void main(String[] args) {

        // Create an input stream
        try (FileReader fr = new FileReader("C:\\test2.txt")) {

            int data;
            // Read a character and print it on console one by one
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }

            // Close input stream automatically when exit the try block
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output:

This is file test2.txt
This is Java 7 example - Manage single resource with try-with-resources

Java 7 Example – Manage Multiple Resources

In this example, we manage multiple resources using try-with-resources statement.

C:\test3.txt

This is file test3.txt
This is Java 7 example - Manage multiple resources with try-with-resources

C:\test4.txt

This is file test4.txt
This is Java 7 example - Manage multiple resources with try-with-resources

TryWithResourcesMutipleResourcesExample.java

package com.chankok.io;

import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesMutipleResourcesExample {

    public static void main(String[] args) {

        // Create 2 input streams
        try (FileReader fr1 = new FileReader("D:\\test3.txt");
             FileReader fr2 = new FileReader("D:\\test4.txt")) {

            int data;

            // Read a character and print it on console one by one
            while ((data = fr1.read()) != -1) {
                System.out.print((char) data);
            }

            // Print new line on console
            System.out.println();

            // Read a character and print it on console one by one
            while ((data = fr2.read()) != -1) {
                System.out.print((char) data);
            }

            // Close 2 input streams automatically when exit the try block
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output:

This is file test3.txt
This is Java 7 example - Manage multiple resources with try-with-resources
This is file test4.txt
This is Java 7 example - Manage multiple resources with try-with-resources

Java 7 Example – Implement Custom AutoCloseable Resource

You can create a custom resource that implement the java.lang.AutoCloseable interface and use it in try-with-resources statement.

MyResource.java

package com.chankok.io;

public class MyResource implements AutoCloseable {

    // Override the close() method
    @Override
    public void close() throws Exception {
        System.out.println("MyResource - close()");

        // ...
    }

    // Implement custom method
    public void myMethod() {
        System.out.println("MyResource - myMethod()");

        // ...
    }

}

TryWithResourcesCustomResourceExample.java

package com.chankok.io;

public class TryWithResourcesCustomResourceExample {

    public static void main(String[] args) {

        // Create a resource
        try (MyResource myResource = new MyResource()) {
            // Run the resource method
            myResource.myMethod();

            // Close the resource automatically when exit the try block
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Output:

MyResource - myMethod()
MyResource - close()

Other Resources