Java try with resource

When we develop an application or project, we use many resources to achieve the task. All the resources must be closed after the program is finished using it. A resource is just an object that we used to perform operations. But sometimes we forget to close the resource after completion of execution and that leads the errors. In this post, we will see how to close the resource automatically by use of java try with resource. Please read the working of a try from here.

Java try with resource

Try with resources in java was introduced in java 7 before moving further we should know how we are working without try with resource and what type of problems we are facing before try with resources java 7.

Without try with resource in java example

Suppose we have a text file in C drive, and we want to read it. Then we create an object of BufferedReader that is known as a resource. After completion of work we have to close the resource (close the object of BufferedReader).

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WithoutTryResource 
{
	public static void main(String[] args) 
	{
		BufferedReader br = null;
		try 
		{
			br = new BufferedReader(new FileReader("C:\\JavaGoal.txt"));
			System.out.println(br.readLine());
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
			try 
			{
				if (br != null)
				   br.close();
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
		}
	}
}

In the above example, we are performing some steps to read the file data. Here we are creating an object of BufferedReader class that is known as a resource. This resource is used to read the data from the file.

After completion of the reading we ae closing the resource in the finally block. The finally block is only used to close the resource, there is no other use in the program.

With try with resources in java 7 example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WithTryResource 
{
	public static void main(String[] args) 
	{
		try(BufferedReader br = new BufferedReader(new FileReader("C:\\JavaGoal.txt"));) 
		{
			System.out.println(br.readLine());
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
	}
}

Here you can see we are creating an object between the braces of try and it automatically gets close after completion of execution.

NOTE: The resource must implement the java.lang.AutoCloseable interface.

  1. It provides a more readable code that can be easy to write and understand.
  2. The best part is Automatic resource management. It automatically closes the resource after use so that developer feels free to headache to close resource.
  3. Minimized the code. It reduced the number of lines in code. Because now there is no need to place a finally block just to close the resources.

Java try with resources multiple resources

We can use the multiple resources in the try-with-resources statement by separating them with a semicolon “;”.

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

class WithTryResource 
{
  public static void main(String[] args) throws IOException
  {
    try (Scanner scanner = new Scanner(new File("testRead.txt")); 
      PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) 
    {
      while (scanner.hasNext()) 
      {
        writer.print(scanner.nextLine());
      }
    }
  }
}

Leave a Comment