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, 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.basic;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class TryWithResourceExample {
    public static void main(String[] args) {
        try {
            TryWithResourceExample demo = new TryWithResourceExample();
            demo.printStream("F:/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, StandardCharsets.UTF_8))) {

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.