2013-04-10 61 views
0

,我提交了代码Veraocode安全测试工具,我得到这个资源不正确关机或在下面的代码发布:如何解决资源不正确关闭或释放问题

//This function is used to print trace in the in the LogFile for debugging purpose 
PrintWriter f; 
      try { 
       f = new PrintWriter(new BufferedWriter(new FileWriter(fileName,true)));//issue at this line 
       synchronized(this) { 
        f.println(new StringBuffer(dateString).append("<").append(Thread.currentThread().getName()).append(">").append(traceLog).toString()); 
       } 
       f.close(); 
       checkFileSize(); 
      }catch(IOException e){  
       e.printStackTrace(); 
      } 

有人请帮助我在这..

回答

0

您需要关闭您的PrintWriter。

f.close(); 
0
 try { 
      f = new PrintWriter(new BufferedWriter(new FileWriter(fileName,true)));//issue at this line 
      synchronized(this) { 
       f.println(new StringBuffer(dateString).append("<").append(Thread.currentThread().getName()).append(">").append(traceLog).toString()); 
      } 

      checkFileSize(); 
     }catch(IOException e){  
      e.printStackTrace(); 
     } finally { 
      if (f != null) { 
       f.close(); 
      } 
     } 

资源应该在最后条款关闭。所以他们肯定会被执行。因为如果您尝试关闭代码,并且在结束行之前发生一些异常。该资源没有正确关闭。

另外,如果您使用的是JDK-7,请查看try-with-resources。

0

您需要关闭catch块中的PrintWriter,或者也可以创建finally块并关闭资源。

}catch(IOException e){  
e.printStackTrace(); 
f.close(); 
} 

OR

finally { 
if (f != null) { 
f.close(); 
} 
}