Java try with resources

Java 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. Java try with resources was introduced in Java 7.

This new feature of Java try with resources statement ensure 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 Java 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.


try(//open your resource(s) here ){
        // Open resource (e.g FileStream)
    }
    // no need of finally, JVM will handle it for us

 

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  Java 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 custom resource, you need to implement AutoCloseable interface

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

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

Reference

  1. try-with-resources
  2. AutoCloseable
  3. Closeable

You May Also Like

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz