Java 7: Try with resources

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

The feature try with resources is included in JSE7. A resource is an object, could be a file or a connection, which must be closed when the program doesn’t use it anymore. By using this feature you ensure to close the resources after using them.

I used the path “/home/gardun/Documents/mydoc” because I work on Linux, but for windows users that is something like: “C:\\mydoc.txt”. For more info click here to read Oracle’s explanation.

Example 1: Try with resources statement code

What happens if the following code is compiled and run?


public class MyClass
  public static void main(String args[])
    // Try with resources
    try(FileOutputStream fos = new FileOutputStream("/mydoc"))
      String message = "Write message to mydoc!";
      byte arrayBytes[] = message.getBytes();
    catch(IOException e)
Author: Sar Maroof

Answer explanation

The message “Write this message to the file mydoc!” will be written to the file if no excetptions are occurred and “Done!” is written to the standard output. In case that an exception is occurred for example the file is not found, the catch block is executed.

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply