Java – try with resources – introduced in Java 7 – allows us to declare resources to be used in a try block which ensures that the resources will be closed when after execution of that block. The resource is an object that should be closed after the execution of try block. The resources declared must implement the AutoCloseable interface.

Resources which implements AutoCloseable interface are listed at the end of article.

1. Using try-with-resources

try-with-resources is simply initialized inside the try as shown below, the resource used should implement the AutoCloseable interface.

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

2. Replacing trycatch-finally with try-with-resources

Let’s compare the following code samples – first is a typical try-catch-finally block, then we will replace, using an equivalent try-with-resources block:

Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

And here’s the compact solution using try-with-resources:

try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

3. try-with-resources with Multiple Resources

Multiple resources can be declared just fine in a try-with-resources block by separating them with semicolon:

try (Scanner scanner = new Scanner(new File("ReadTest.txt"));
    PrintWriter writer = new PrintWriter(new File("WriteTest.txt"))) {
    while (scanner.hasNext()) {
    writer.print(scanner.nextLine());
    }
}

4. A Custom Resource with AutoCloseable

To construct a custom resource that will be correctly handled by a try-with-resources block, the class should implement the Closeable or AutoCloseable interfaces, and override the close method:

public class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Message for close call.");
    }
}

5. Resource Closing Order

Resources that were defined/acquired first will be closed last. Let’s look at an example of this behaviour:

Resource 1:
public class AutoCloseableResourcesFirst implements AutoCloseable {
 
    public AutoCloseableResourcesFirst() {
        System.out.println("Constructor call for first AutoCloseableResources");
    }
 
    public void myProgram() {
        System.out.println("Program call-> First AutoCloseableResources");
    }
 
    @Override
    public void close() throws Exception {
        System.out.println("In Close Call of AutoCloseableResources");
    }
}
Resource 2:
public class AutoCloseableResourcesSecond implements AutoCloseable {
 
    public AutoCloseableResourcesSecond() {
        System.out.println("Constructor call for Second AutoCloseableResources");
    }
 
    public void myProgram() {
        System.out.println("Program call-> second AutoCloseableResources");
    }
 
    @Override
    public void close() throws Exception {
        System.out.println("In Close Call of second AutoCloseableResources");
    }
}
Code:
private void orderOfClosingResources() throws Exception {
    try (AutoCloseableResourcesFirst ab = new AutoCloseableResourcesFirst();
        AutoCloseableResourcesSecond cd = new AutoCloseableResourcesSecond()) {
 
        ab.myProgram();
        cd.myProgram();
    }
}
Output:

Constructor call for first AutoCloseableResources
Constructor call for Second AutoCloseableResources
Program call-> First AutoCloseableResources
Program call-> second AutoCloseableResources
In Close Call of first AutoCloseableResources
In Close Call of second AutoCloseableResources

6. catch & finally

try-with-resources block can still have the catch and finally blocks – which will work in the same way as with a traditional try block.

All Known Implementing Classes of AutoCloseable:

AbstractInterruptibleChannel, AbstractSelectableChannel, AbstractSelector, AsynchronousFileChannel, AsynchronousServerSocketChannel, AsynchronousSocketChannel, AudioInputStream, BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream, CharArrayReader, CharArrayWriter, CheckedInputStream, CheckedOutputStream, CipherInputStream, CipherOutputStream, DatagramChannel, DatagramSocket, DataInputStream, DataOutputStream, DeflaterInputStream, DeflaterOutputStream, DigestInputStream, DigestOutputStream, FileCacheImageInputStream, FileCacheImageOutputStream, FileChannel, FileImageInputStream, FileImageOutputStream, FileInputStream, FileLock, FileOutputStream, FileReader, FileSystem, FileWriter, FilterInputStream, FilterOutputStream, FilterReader, FilterWriter, Formatter, ForwardingJavaFileManager, GZIPInputStream, GZIPOutputStream, ImageInputStreamImpl, ImageOutputStreamImpl, InflaterInputStream, InflaterOutputStream, InputStream, InputStream, InputStream, InputStreamReader, JarFile, JarInputStream, JarOutputStream, LineNumberInputStream, LineNumberReader, LogStream, MemoryCacheImageInputStream, MemoryCacheImageOutputStream, MLet, MulticastSocket, ObjectInputStream, ObjectOutputStream, OutputStream, OutputStream, OutputStream, OutputStreamWriter, Pipe.SinkChannel, Pipe.SourceChannel, PipedInputStream, PipedOutputStream, PipedReader, PipedWriter, PrintStream, PrintWriter, PrivateMLet, ProgressMonitorInputStream, PushbackInputStream, PushbackReader, RandomAccessFile, Reader, RMIConnectionImpl, RMIConnectionImpl_Stub, RMIConnector, RMIIIOPServerImpl, RMIJRMPServerImpl, RMIServerImpl, Scanner, SelectableChannel, Selector, SequenceInputStream, ServerSocket, ServerSocketChannel, Socket, SocketChannel, SSLServerSocket, SSLSocket, StringBufferInputStream, StringReader, StringWriter, URLClassLoader, Writer, XMLDecoder, XMLEncoder, ZipFile, ZipInputStream, ZipOutputStream

 

Please follow and like us:
error