☰ See All Chapters |
Java 9 try with resources improvements
A resource is an object that must be closed after the program is finished with it. Resource may be a Database like MySQL, Oracle. Resource may be a file. Resource may be a socket connection Etc… When we connect to database, we must explicitly close database connection before JVM shutdown. If we open a file we must explicitly close file before JVM shutdown and so on. In order close these resources we generally use finally block (till java 6) since finally block always executes irrespective of exceptions and errors.
The try with resources statement is a try statement that declares one or more resources. The try with resources statement ensures that each resource is closed at the end of the try block execution.
Any object that implements java.lang.AutoCloseable, and java.io.Closeable interfaces can be used as a resource. AutoCloseable interface is also introduced in java 1.7
From java 9 we can use the resource instantiated outside the try with resource statements effectively as shown below:
package com.java4coding;
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;
class Demo { static String readFirstLineFromFile(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try (br) { return br.readLine(); } } }
public class Test { public static void main(String[] args) throws IOException { String s = Demo.readFirstLineFromFile("I:/A.txt"); System.out.println(s); } } |
Closing resources in Java 7
In java 7 resources should be instantiated inside try with resource statement.
package com.java4coding.test;
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;
class Demo { static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } }
public class Test { public static void main(String[] args) throws IOException { String s = Demo.readFirstLineFromFile("I:/A.txt"); System.out.println(s); } } |
Closing resources prior Java 7
package com.java4coding.test;
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;
class Demo { static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } } }
public class Test { public static void main(String[] args) throws IOException { String s = Demo.readFirstLineFromFileWithFinallyBlock("I:/A.txt"); System.out.println(s); } } |
All Chapters