How to make sure resources are auto-closed in Java?

Prior to Java 7 , if we wanted to close a resource like a FileOutputStream we had to do it inside a finally block.

And the code looked something like this :


	private static void theoldway() {
		FileOutputStream f = null;
		try {

			// do something here

			// open a file output stream.
			f = new FileOutputStream(new File("try.txt"));
			
			f.write(100);

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {

				if (f != null) {
					f.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

We had to check if the resources is null in the finally block and again add a try-catch block as closing the resource could throw IOException.

This got far simplified in Java 7. There is no need to close a resource. Java automatically takes care of it.

All we have to do is use a try with resources block like below:


	private static void thenewway() {
		
		//do something here
		
		try(FileOutputStream f = new FileOutputStream(new File("try.txt"))){
			

			f.write(100);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Just add a open parantheses next to try statement, create the resource inside it and then close the parantheses . Follow it by the regular open curly braces.

Not only the code is less error prone now, it is shorter.

Handling multiple resources:

What if there are multiple resources used in a method? We can include all of them within the same parantheses separated by semi colons like this :

try(FileOutputStream f = new FileOutputStream(new File("try.txt"));FileInputStream reader = new FileInputStream(new File("new.text"))){



}

In the above case , FileInputStream will be closed followed by FileOutputStream , that is whichever is declared first will be closed last (reverse order).

What are the resources that can be automatically closed this way?

Anything which implements AutoCloseable or Closeable (which in turn extends AutoCloseable) interface provided by Java. In the above example , FileOutputStream extends OutputStream which implements Closeable interface.


Posted

in

by

Tags:

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading