2013-04-10 63 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(); 
} 
}