资源释放

分析

  在使用文件、IO 流、数据库连接等不会自动释放的资源时,应该在使用完毕后马上将其关闭。关闭资源的代码应该在try...catch...finally的 finally内执行,否则可能造成资源无法释放。


示例

  关闭IO 流的正确方法如下:

  /**
     * IO,数据库操作资源释放示例
     * @param filePath
     * @param strContent
     * @throws FileNotFoundException
     */
    public void writeFile(String filePath,String strContent) throws FileNotFoundException
    {
        PrintWriter printer = null;
        try
        {
            printer = new PrintWriter(new FileOutputStream(filePath));
            printer.print(strContent);
            
        }
        catch(IOException ex)
        {
            //此处应记录日志
            ex.printStackTrace();
        }
        finally
        {
            printer.close();//释放资源必须放在finally里面进行释放。
            
            //若有多个资源需要释放应使用
            /*try
            {
                //释放资源
            }
            catch (Exception e)
            {
                // TODO: handle exception
                //记录日志
            }
            
            try
            {
                //释放资源
            }
            catch (Exception e)
            {
                // TODO: handle exception
                //记录日志
            }*/
        }
    }

注意:在捕获异常后一定要记录日志。 

posted on 2012-10-17 10:53  云中雁荡山  阅读(218)  评论(0编辑  收藏  举报

导航