Try with Resources

In Java, we open a file in a try block and close it in finally block to avoid any potential memory leak.try-with-resources introduced in Java 7. This new feature of try-with-resources statement ensures that resources will be closed after execution of the program. Resources declared under try with java resources must implement java.lang.AutoCloseable interface.

Here are few of the advantages of using try-with-resources statement.

  1. You don’t have to close resource explicitly, close() is automatically called by JVM, if it throws an IOException, it will be suppressed. (Call it automatic resource management)
  2. More clean and concise code.
  3. Ability to open multiple resources and manage them automatically.

Before Java 7, We will handle resource in following way

try{
      // Open resource (e.g FileStream)
    }
    catch(IOException exception){
        //exception handling
    }
    finally{
        //block to close resoucres opened in try block
    }

Java 7  try with resources introduced a more easy way to handle it.

Using try-with-resources

try(//open your resource(s) here ){
        // Open resource (e.g FileStream)
    }
    // no need of finally, JVM will handle it for us
  
  // Example
   try (PrintWriter writer = new PrintWriter(new File("file.txt"))) {
    writer.println("Hello World");
}

Pay close attention to try(//open your resource(s) here ) which is the new and main block for Java try with resource feature.

 

1. Resource Handling Pre Java 7

public class FIleIOPreJDK7 {

    public static void main(String[] args) throws FileNotFoundException {

        String fileName = "/tutorials/fileread/SampleFile.txt";
        String fileContent;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
        try {

            while ((fileContent = bufferedReader.readLine()) != null) {
                //business logic for file processing
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();   // we need to close it to avoid memory leak.
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}

 

2. With Java 7

public class FileIOWithJava7 {

    public static void main(String[] args) {

        String fileName = "/tutorials/fileread/SampleFile.txt";

        try( BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName))){
            String content;
            while((content = bufferedReader.readLine() )!=null){
                //you logic here
            }
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

In the above example,  the resource declared in the try-with-resources statement is a BufferedReader. Resource declaration appears within parentheses immediately after the try keyword.You must have noticed that there is no finally in the code, try with resource statement will automatically close BufferReader once program complete try block.

In this section, we will cover other features of try-with-resources.

 

3. Try with resources for multiple Resources

try with resources can efficiently be used for multiple resources

public class MultipleResouces {

    public static void main(String[] args) {

        String fileName = "/tutorials/fileread/SampleFile.txt";
        String fileName1 = "/tutorials/fileread/SampleFile1.txt";

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
             Scanner scanner = new Scanner(new File(fileName1))) {
            String content;
            while ((content = bufferedReader.readLine()) != null) {
                //you logic here
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

Multiple resources can be declared within try block by using

; (try (BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
             Scanner scanner = new Scanner(new File(fileName1))))

 

4. Custom Resource

To create a custom resource, you need to implement AutoCloseable interface

MyCustomResource impliments AutoCloseable{
  @Override 
  public void close() throws Exception{
     //you need to impliment close method
  }
}

 

5. catch & finally

try-with-resources block can still have the catch and finally blocks. This approach is similar to the old or traditional way to try statement in Java.

 

6. Improvement with JDK9

As per of the Milling Project Coin in JDK 9, there is further improvement in the Java try-with-resources statement which is more natural” way of writing.If you already have a resource as a final or a final variable, you can easily use this variable in try statement without declaring any a new variable

Before JDK9

// BufferedReader is declared outside try() block
BufferedReader br = new BufferedReader(new FileReader("file-path"));

try (BufferedReader inBr = br) {
    // ...
} catch (IOException e) {
    // ...
}

With JDK9

// JDK9
BufferedReader br = new BufferedReader(new FileReader("file-path"));

try (br) {
    // use the reader
} catch (IOException e) {
    // ignoring exceptions because that is how I roll
}

All the code of this article is available Over on Github. This is a Maven-based project.

Reference

  1. JDK Doc
  2. AutoCloseable
  3. Closeable