12 September, 2013

Close Resources in Java

In java when using any resources like Files, Streams, Database Connection and DataSets etc .... , you must close resources at end of processing at your code.

For Example : Streams 

        File f = new File("myFile.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            // Do something...
        } catch (FileNotFoundException ex) {
            // Display error message
        } finally {
            // Closing resource
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use IOUtils Appache packages  to close resources quietly
      finally{
   IOUtils.closeQuietly(fos);
      }


For Example : Database Statement

 finally{
   DBTransaction txn = this.getDBTransaction();
        String sqlStmt =
            "Begin plsqlCode; END;";
        CallableStatement callStmt =
            txn.createCallableStatement(sqlStmt, DBTransaction.DEFAULT);
        try {
             //Write your code here to work with CallableStatement 
        } catch (SQLException e) {
             //Handle SQL Exception
        }finally {
            // Closing resource
            if (callStmt != null) {
                try {
                    callStmt .close();
                } catch (SQLException ex) {
                    //Here , Hide Exception
                }
            }
        }

All previous code in Blue color are used to close resources.
So to save time and make code more readability you can use DBUtils Appache packages  to close resources quietly

      finally{
   DbUtils.closeQuietly(callStmt );
      }

Thanks

No comments:

Post a Comment

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope. There are five scopes in ADF (Application, Request, Session, View and PageFl...