如何解决不正确的资源关闭或发布问题

时间:2013-04-10 11:45:24

标签: java security veracode

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

有人请帮助我...

3 个答案:

答案 0 :(得分:2)

您需要关闭PrintWriter。

f.close();

答案 1 :(得分: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();
             }
        }

应该在finally子句中关闭资源。这样他们肯定会被执行。因为如果你把关闭代码放在try中,并且在关闭行之前会发生一些异常。资源无法正常关闭。

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

答案 2 :(得分:0)

您还需要在catch块中关闭PrintWriter或者创建finally块并关闭资源。

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

OR

finally {
if (f != null) {
f.close();
}
}
相关问题