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)
Contents
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(); } } } } |
– After reading a file, we take a risk if developers do Not remember to close resources.
– Source code is not clear & clean:
finally { try { if (null != br) br.close(); } catch (IOException e) { e.printStackTrace(); } } |
So how to improve it?
2. Java 7 – New Approach by try-with-resources statement
By try-with-resources statement, our code is clear and clean. Developers do NOT need to close the resources so one risk is auto removed.
package com.javasampleapproach.trywithresources; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileWithJava7 { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"))) { String line; while (null != (line = br.readLine())) { // processing each line of file System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } |
That is better? Right!
IV. Source code
Last updated on July 1, 2017.