Tuesday, November 25, 2014

Java 7 resources management

 Did you know that there is a really better way to close resources in Java 7? Yes, before Java 7, you should always explicity close connections, files, datasources or others resources after using them.

This used to be done like this:

     FileOutputStream fos = null;  
     try {  
       fos = new FileOutputStream("test.txt");  
       // do something cool with fos  
     } catch (FileNotFoundException e) {  
       // catch code  
     } catch (IOException e) {  
       // catch code  
     } finally {  
       try {  
         fos.close();  
       } catch (Exception ex) {  
         // log the exception  
       }  
     }  


Now, if you are using Java 7, you just would have to write this code:
  
  try (FileOutputStream fos = new FileOutputStream("test.txt")) {  
     // do something cool with fos  
  } catch (FileNotFoundException e) {  
     e.printStackTrace();  
  } catch (IOException e) {  
     e.printStackTrace();  
  }  


Realize that the recource declaration have to be written on the new try() and that you have to use a resource that implements java.lang.AutoClosable interface.

Best regards!

No comments:

Post a Comment