There are a lot of cases where we have to work with resources such as streams,database connections etc that must be closed after after using them.

Prior Java 7 closing resources was done manually usually in the finally part of a try statement.For example:

 

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.logging.Level;
import java.util.logging.Logger;


public class Java7test {

    
    public static void main(String[] args) {
         FileInputStream stream=null;
         BufferedInputStream reader=null;
        File file=new File("C:\\file.txt");
        try {
            stream=new FileInputStream(file);
            reader=new BufferedInputStream(stream);
            while(reader.read()!=-1){
                
            }
            reader.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Java7test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Java7test.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Java7test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
        
}

Java 7 introduced try-with-resources statement where resources such as streams and connections are automatically handled and closed.

So the above example can be re-written using try-with-resources statement as follows:


package java7test;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.logging.Level;
import java.util.logging.Logger;


public class Java7test {

    
    public static void main(String[] args) {
         
        
        File file=new File("C:\\file.txt");
        try( BufferedInputStream reader=new BufferedInputStream(new FileInputStream(file))) {
            
            
            while(reader.read()!=-1){
                //something useful happens here
            }
           
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Java7test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Java7test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        
}

As you can see in the above example reader stream is declared and initialized inside try's parentheses.Note that resources that are handled by try-with-resources statement should implement AutoClosable or Closable interface.

Note also that finally clause are still valid in try-with-resources statement but the code in the finally clause will be executed after the resources declared in the parentheses are closed