Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Monday, November 2, 2015

Try-with-Resources in Java

It is a fairly common mistake by Java programmers to forget releasing resources, even in the finally block. Also, if you’re dealing with multiple resources, it is tedious to remember to call the close() method in the finally block. Java 7 introduced a feature named try-with-resources to help make your life easier.

Make sure you take a closer look at the syntax for try-with-resources block.

try(Scanner consoleScanner = new Scanner(System.in)) {
The Java compiler will internally translate this try-with-resources block into a try-finally block (of course, the compiler will retain the catch blocks you provide).
You can acquire multiple resources in the try-with-resources block; such resource acquisition statements should be separated by semicolons.

Can you provide try-with-resources statements without any explicit catch or finally blocks? Yes! Remember that a try block can be associated with a catch block, finally block, or both.

Note that for a resource to be usable with a try-with-resources statement, the class of that resource must implement the java.lang.AutoCloseable interface.

Closing Multiple Resources

You can use more than one resource in a try-with-resources statement.

ZipTextFile.java

package com.appfworks.exception;

/**
* Created by suresh on 02/11/15.
*/
import java.util.*;
import java.util.zip.*;
import java.io.*;
// class ZipTextFile takes the name of a text file as input and creates a zip file
// after compressing that text file.
class ZipTextFile {
public static final int CHUNK = 1024; // to help copy chunks of 1KB
public static void main(String []args) {
if(args.length == 0) {
System.out.println("Pass the name of the file in the current directory to be zipped as an argument");
System.exit(-1);
}
String fileName = args[0];
// name of the zip file is the input file name with the suffix ".zip"
String zipFileName = fileName + ".zip";
byte [] buffer = new byte[CHUNK];
// these constructors can throw FileNotFoundException
try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName));
FileInputStream fileIn = new FileInputStream(fileName)) {
// putNextEntry can throw IOException
zipFile.putNextEntry(new ZipEntry(fileName));
int lenRead = 0; // variable to keep track of number of bytes
// successfully read
// copy the contents of the input file into the zip file
while((lenRead = fileIn.read(buffer)) > 0) {
// both read and write methods can throw IOException
zipFile.write (buffer, 0, lenRead);
}
// the streams will be closed automatically because they are
// within try-with-resources statement
}
// this can result in multiple exceptions thrown from the try block;
// use "suppressed exceptions" to get the exceptions that were suppressed!
catch(Exception e) {
System.out.println("The caught exception is: " + e);
System.out.print("The suppressed exceptions are: ");
for(Throwable suppressed : e.getSuppressed()) {
System.out.println(suppressed);
}
}
}
}


Suppressed exceptions

In a try-with-resources statement, there might be more than one exception that could get thrown; for example, one within the try block, one within the catch block, and another one within the finally block. However, only one exception can be caught, so the other exception(s) will be listed as suppressed exceptions. From a given exception object, you can use the method getSuppressed() to get the list of suppressed exceptions.

No comments:

Post a Comment