Java: Try With Resources

Reading Time: 2 minutes

Try with resources is a special type of try statement where we can declare more than one resources within a single try statement. This feature came in Java 7. But it has some limitation with itself that overcomes in Java 9.

https://gist.github.com/er-rishi/db16acf92d89a973111ff22e36b7cb4b

We will discuss this limitation through the examples. Now, Firstly we have to know what is resource actually, A resource is an object that must be closed after the program is finished with it. Now, we will come to what is try with resources?

The try with resources statement ensures that each one of the resources is closed at the end of the statement.

We will go through one example first how we close the resources before try with resources came into the picture.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
countWords("sample.txt");
}
/**
* this method count number of words from the text file and finally print the number of words * * @param fileName
*/
public static void countWords(String fileName) {
try {
long wordCount = Files.lines(Paths.get(fileName))
.flatMap(str > Stream.of(str.split("[ ,.!?\r\n]"))).count();
System.out.println("Number of words in file : " + wordCount);
} catch (FileNotFoundException fnf) {
System.out.println("Exception Occurred" + fnf.getMessage());
} catch (IOException io) {
System.out.println("Exception Occurred" + io.getMessage());
}
}
}

view raw
WordCounts.java
hosted with ❤ by GitHub

So, the above example shows how we close the resources before try with resources feature. There was no automated way to close the resources we have to explicitly close the resources at last.

Now, we will go through one more example where we used try with resources that came in Java 7.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
countWords("sample.txt");
}
/**
* this method count number of words from the text file and finally print the number of words * * @param fileName
*/
public static void countWords(String fileName) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
long wordCount = stream.flatMap(str > Stream.of(str.split("[ ,.!?\r\n]"))).count();
System.out.println("Number of words in file : " + wordCount);
} catch (FileNotFoundException fnf) {
System.out.println("Exception Occurred" + fnf.getMessage());
} catch (IOException io) {
System.out.println("Exception Occurred" + io.getMessage());
}
}
}

view raw
WordCount.java
hosted with ❤ by GitHub

The above example has one limitation the Stream object we can only use within try block so the scope of that resource object that we declared with the try statement is local.

So, at last, we will go through with one more example to see how Java 9 overcome or solve this problem.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class WordCount {
public static void main(String[] args) throws IOException {
countWords("sample.txt");
}
/**
* this method count number of words from the text file and finally print the number of words
*
* @param fileName
*/
public static void countWords(String fileName) throws IOException {
Stream<String> stream = Files.lines(Paths.get(fileName));
try (stream) {
long wordCount = stream.flatMap(str > Stream.of(str.split("[ ,.!?\r\n]")))
.count();
System.out.println("Number of words in file : " + wordCount);
} catch (Exception e) {
System.out.println("Exception Occurred" + e.getMessage());
}
}
}

view raw
CountWords.java
hosted with ❤ by GitHub

This example is self-explanatory itself. So, from the Java 9, we can pass the resource references that we can’t do till Java 8. And the scope problem is also resolved.

Note:- Any object that implements java.lang.AutoCloseable, which includes all objects which implement,java.io.Closeable can be used as a resource.

references :
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Happy Blogging 🙂


knoldus-advt-sticker


 

Written by 

Kunal Sethi is a Software Consultant with experience of more than 2.5 years. He is a Java enthusiast and has knowledge of various programming languages such as Scala, C++. He is familiar with Object-Oriented Programming Paradigms, loves to code applications in J2EE. He developed his own stand-alone application in Java based on the intranet chatting System and email system during his Master's Degree.