# The try-with-resources statement

In 
Published 2024-01-06

This tutorial explains the try-with-resources statement in Java.

In Java any connection to a printer, to a file, to a network, etc could keep the resource busy. For instance if you open a file to write or to read something into it, it is possible to lock that object/resource. In addition, that connection consumes some memory.

For all these reasons it is a good thing to use that resource and after that to close the connection and to release the resource.

For doing this take we can use the classical "try ... catch ... finally" statement. In "finally" block we can close the resource.

Take a look at the following example:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(Demo1Application.class, args);

		String fileName = "D:\\test-java\\demo1\\src\\main\\resources\\sentence.txt";
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(fileName);

			int i;

			while ((i = fis.read()) != -1) {
				System.out.print((char) i);
			}

		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);

		} catch (IOException e) {
			throw new RuntimeException(e);

		} finally {
			if (fis != null) {
				fis.close();
			}
		}

		System.out.println("");
		System.out.println("END");
	}
}

All looks good, but the same thing is done by using "try-with-resources" statement.

Take a look at the example below:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);

		String fileName = "D:\\test-java\\demo1\\src\\main\\resources\\sentence.txt";

		try (FileInputStream fis = new FileInputStream(fileName)) {

			int i;

			while ((i = fis.read()) != -1) {
				System.out.print((char) i);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);

		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		System.out.println("");
		System.out.println("END");
	}
}

In both cases when we have an error or not, the resource is closed.