DEV Community

loizenai
loizenai

Posted on

Java 7 – try-with-resources Statement

https://grokonez.com/java/java-advanced/java-7-try-with-resources-statement

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


package com.javasampleapproach.trywithresources;

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

public class ReadFileByJava6OrEarly {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("C://readfile/input.txt"));
            String line;
            while (null != (line = br.readLine())) {
                // process each line of File
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != br)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

More at:

https://grokonez.com/java/java-advanced/java-7-try-with-resources-statement

Java 7 – try-with-resources Statement

Top comments (0)