Core Java

Java AutoCloseable Interface Example

In this tutorial we will discuss about the AutoCloseable interface in Java. This interface represents an object that holds its resources until it is closed. Examples of such resources are a file handler and a socket handler.

The close() method of an Object that implements the AutoCloseable interface is called automatically, when exiting a try-with-resources block and that object has been declared in the resource specification header.

The AutoCloseable interface exists since the 1.7 version of Java.

 

The try-with-resources statement

The try-with-resources statement is a try statement, introduced in Java 1.7, which declares a number of resources. The resources are objects that must be closed, once an application stops processing them, in order to be collected by the Garbage Collector and for memory space to be reclaimed. A try-with-resources statement makes sure that all declared resources will be closed at the end of the statement. Thus, this statement aims to ensure proper release of resources, avoiding memory exhaustion and possible errors that may occur.

Any object that implements the AutoCloseable interface can be considered as a resource. An example using the try-with-resources statement is shown below:

TryWithResourcesExample.java:

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

public class TryWithResourcesExample {
	private final static String FILENAME = "file1.txt";

	public static void main(String[] args) {
		try(BufferedReader rd = new BufferedReader(new FileReader(FILENAME))) {
			String inputLine = null;
			
			while((inputLine = rd.readLine()) != null)
				System.out.println(inputLine);
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}

In this example, we declare an instance of the BufferedReader class, in order to read the contents of the file specified by the FILENAME constant.

As you can observe, we have skipped the close() method of the BufferedReader class, due to the fact that it is called automatically by the try-with-resources statement.

A sample execution is shown below:

Hello from
Java Code Geeks!

In versions before Java 1.7, a resource was closed inside the finally statement, in order to ensure that the resource was successfully closed, regardless of whether the try statement completes normally or not. Thus, our previous example would be transformed to:

TryCatchFinallyExample.java:

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

public class TryCatchFinallyExample {
	private final static String FILENAME = "file1.txt";
	
	public static void main(String[] args) {
		BufferedReader rd = null;
		try {
			rd = new BufferedReader(new FileReader(FILENAME));
			String inputLine = null;
			
			while((inputLine = rd.readLine()) != null)
				System.out.println(inputLine);
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			if(rd != null) {
				try {
					rd.close();
				}
				catch (IOException ex) {
					System.err.println("An IOException was caught: " + ex.getMessage());
					ex.printStackTrace();
				}
			}
		}
	}
}

The AutoCloseable Interface in Java

A large number of classes implements the AutoCloseable interface. In this section, we will describe some of them and we will demonstrate examples where multiple resources are declared inside a try-with-resources statement. Every class that implements the AutoCloseable interface must define the behaviour of the close() method.

BufferedReader-BufferedWriter example

In this example we will copy the contents of one source file to another destination file, using instances of the BufferedReader class and BufferedWriter class respectively:

FileCopyExample.java:

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

public class FileCopyExample {
	private final static String INPUT = "in.txt";
	private final static String OUTPUT = "out.txt";
	
	public static void main(String[] args) {
		try(BufferedReader rd = new BufferedReader(new FileReader(INPUT));
			BufferedWriter wr = new BufferedWriter(new FileWriter(OUTPUT)))
		{	
			String inputLine = null;
			
			// Print the content of the input file and in parallel,
			// execute the copy procedure line-by-line.
			System.out.println("The input file contains the following lines:");
			while((inputLine = rd.readLine()) != null) {
				System.out.println(inputLine);
				wr.write(inputLine + "\n");
			}
			
			// Make sure that every data is written to the output file.
			wr.flush();
			
			System.out.println("\nThe copy procedure has been successfully completed!");
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}

Notice that multiple resource definitions are separated by the ; character.

A sample execution is shown below:

The input file contains the following lines:
Hello from
Java Code Geeks!

The copy procedure has been successfully completed!

PrintStream example

In this example, we will copy the contents of one source file to another destination file, but instead of using an instance of the BufferedWriter class, we will use an instance of the PrintStream class:

PrintStreamExample.java:

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

public class PrintStreamExample {
	
	private final static String INPUT = "in.txt";
	private final static String OUTPUT = "out.txt";
	
	public static void main(String[] args) {
		try(BufferedReader rd = new BufferedReader(new FileReader(INPUT));
			PrintStream stream = new PrintStream(new File(OUTPUT)))
		{	
			String inputLine = null;
			
			// Print the content of the input file and in parallel,
			// execute the copy procedure line-by-line.
			System.out.println("The input file contains the following lines:");
			while((inputLine = rd.readLine()) != null) {
				System.out.println(inputLine);
				stream.write((inputLine + "\n").getBytes());
			}
			
			// Make sure that every data is written to the output file.
			stream.flush();
			
			System.out.println("\nThe copy procedure has been successfully completed!");
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}

A sample execution is shown below:

The input file contains the following lines:
Hello from
Java Code Geeks!

The copy procedure has been successfully completed!

FileWriter-StringWriter example

Finally, in this example we will copy the contents of one source file to another destination file, using an instance of the FileWriter class and one instance of the StringWriter class:

StringWriterExample.java:

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

public class StringWriterExample {
	private final static String INPUT = "in.txt";
	private final static String OUTPUT = "out.txt";
	
	public static void main(String[] args) {
		try(BufferedReader rd = new BufferedReader(new FileReader(INPUT));
			FileWriter wr = new FileWriter(OUTPUT);
			StringWriter str = new StringWriter())
		{	
			String inputLine = null;
			
			// Print the content of the input file and in parallel,
			// execute the copy procedure line-by-line.
			System.out.println("The input file contains the following lines:");
			while((inputLine = rd.readLine()) != null) {
				System.out.println(inputLine);
				str.write(inputLine + "\n");
			}
			
			// Make sure that every data is written to the output file.
			wr.write(str.toString());
			wr.flush();
			
			System.out.println("\nThe copy procedure has been successfully completed!");
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}

A sample execution is shown below:

The input file contains the following lines:
Hello from
Java Code Geeks!

The copy procedure has been successfully completed!

Download the Eclipse Project

This was a tutorial about the AutoCloseable interface in Java.

Download
You can download the full source code of this example here: AutoCloseableExamples.zip.

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button