【问题标题】:How to resolve Improper Resource Shutdown or Release issue如何解决不正确的资源关闭或释放问题
【发布时间】:2013-04-02 05:44:14
【问题描述】:

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

请有人帮我解决这个问题...

【问题讨论】:

    标签: java security veracode


    【解决方案1】:

    您需要关闭 PrintWriter。

    f.close();
    

    【讨论】:

      【解决方案2】:
           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。

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2015-03-15
          • 1970-01-01
          • 2016-02-03
          • 2014-12-19
          • 2011-08-12
          • 1970-01-01
          • 2012-01-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多