What is try-with-resource in java?

Whenever we instantiate and use certain objects/resources we should close them explicitly else there is a chance of Resource leak.

From JSE7 onwards the try-with-resources statement is introduced. In this we declare one or more resources in the try block and these will be closed automatically after the use. (at the end of the try block)

The resources we declare in the try block should extend the java.lang.AutoCloseable class.


Following program demonstrates the try-with-resources in Java.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopying {
   public static void main(String[] args) {
      try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt"));
      FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){
         byte[] buffer = new byte[1024];
         int length;
         while ((length = inS.read(buffer)) > 0) {
            outS.write(buffer, 0, length);
         System.out.println("File copied successfully!!");
      catch(IOException ioe) {


File copied successfully!!