簡體   English   中英

如何解決不正確的資源關閉或發布問題

[英]How to resolve Improper Resource Shutdown or Release issue

我提交了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();  
            }   

有人請幫幫我...

您需要關閉PrintWriter。

f.close();
     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();
             }
        }

資源應該在finally子句中關閉。 這樣他們肯定會被執行。 因為如果你把關閉代碼放在try中,並且在關閉行之前會發生一些異常。 資源未正確關閉。

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

您還需要在catch塊中關閉PrintWriter或者創建finally塊並關閉資源。

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM