dsa

Java try-with-resources

In this tutorial, we will learn about the try-with-resources statement to close resources automatically.

In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution.

Syntax


try (resource declaration) 
{
  	// use of the resource
} 
catch (ExceptionType e1) 
{
  	// catch block
}

Example 1


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

public class Javatrywithresources 
{

	public static void main(String[] args) 
	{
		try (BufferedReader br = new BufferedReader(new FileReader("C:\\codemistic.txt"))) 
		{
			line=br.readLine();
			System.out.println("Line =>"+line);
		} 
		catch (IOException e) 
		{
			System.out.println("IOException in try-with-resources block =>" + e.getMessage());
		}
	}
}
Output if the codemistic.txt file is not found.
IOException in try-with-resources block =>codemistic.txt (No such file or directory)
Output if the codemistic.txt file is found.
Line =>test line

In this example, we use an instance of BufferedReader to read data from the codemistic.txt file.

Declaring and instantiating the BufferedReader inside the try-with-resources statement ensures that its instance is closed regardless of whether the try statement completes normally or throws an exception.

If an exception occurs, it can be handled using the exception handling blocks or the throws keyword.

try-with multiple resources

We can declare more than one resource in the try-with-resources statement by separating them with a semicolon ;

Example 2

import java.io.*;
import java.util.*;
class Codemistic 
{
  	public static void main(String[] args) throws IOException
	{
    		try (Scanner scanner = new Scanner(new File("fileRead.txt")); PrintWriter writer = new PrintWriter(new File("fileWrite.txt"))) 
		{
      			while (scanner.hasNext()) 
			{
        			writer.print(scanner.nextLine());
      			}
    		}
  	}
}

When multiple declarations are made, the try-with-resources statement closes these resources in reverse order. In this example, the PrintWriter object is closed first and then the Scanner object is closed.

Java 9 Enhancements

Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we'll use BufferedReader as resource to read a string and then BufferedReader is to be closed.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class Tester 
{
   	public static void main(String[] args) throws IOException 
	{
      		System.out.println(readData("test"));
   	} 
   	static String readData(String message) throws IOException 
	{
      		Reader inputString = new StringReader(message);
      		BufferedReader br = new BufferedReader(inputString);
      		try (BufferedReader br1 = br) 
		{
         		return br1.readLine();
      		}
   	}
}
Output

test

In Java9, we don't need to declare br1 anymore and following program will give the same result.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class Tester 
{
   	public static void main(String[] args) throws IOException 
	{
      		System.out.println(readData("test"));
   	} 
   	static String readData(String message) throws IOException 
	{
      		Reader inputString = new StringReader(message);
      		BufferedReader br = new BufferedReader(inputString);
      		try (br) 
		{
         		return br.readLine();
      		}
   	}
}
Output

test