Home  >  Java 7

try-with-resources for AutoCloseable Class in Java

By Arvind Rai, March 10, 2014
try-with-resources is nothing but a type of try block. Java has introduces this statement in JDK 7. Here we will understand how to use try-with-resources. JDK 7 has introduces an interface that is java.lang.AutoCloseable. The classes like ObjectOutputStream, OutputStream, InputStream etc implement AutoCloseable interface. So while using these classes, we do not need to close them explicitly in finally block. These types of resources will automatically be closed. Find the sample code how to use try-with-resources.
try( FileInputStream fis = new FileInputStream(file) ){
     
}catch(){

} 
We use auto closeable resource within try statement, that is why we say it try-with-resources. If more than one resources are there to use, then use them by comma separated. Find the full example.
TryWithResources.java
package com.concretepage;
import java.io.File;
import java.io.FileInputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class TryWithResources {
	public static void main(String[] args) throws Exception {
		File file = new File("D:/cp/jar/testjar.jar");
		JarEntry je;
	    try(
    		FileInputStream fis = new FileInputStream(file);
    	    JarInputStream jis = new JarInputStream(fis);
	    ){
	    	while((je=jis.getNextJarEntry())!=null){
	        	System.out.println(je.getName());
	    	}
		}
	}
} 
In the above example we can see that two resources has been used with try statement. These resources need not to close, they are auto closeable.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us