How do I use try-with-resources statement?

The try-with-resources statement is introduced in the Java 7. With this new statement we can simplify resource management in our program, it also known as ARM (Automatic Resource Management).

This statement is a try statement that declares one or more resources. After the program finish with the resource it must be closed. The try-with-resources ensures that each resource is closed and the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

package org.kodejava.example.basic;

import java.io.*;

public class TryWithResourceExample {
    public static void main(String[] args) {
        try {
            TryWithResourceExample demo = new TryWithResourceExample();
            demo.printStream("/tmp/data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void printStream(String fileName) throws IOException {
        char[] buffer = new char[1024];

        try (InputStream is = new FileInputStream(fileName);
             Reader reader = new BufferedReader(
                     new InputStreamReader(is, "UTF-8"))) {

            while (reader.read(buffer) != -1) {
                System.out.println(buffer);
            }
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply