0

I submitted my code for Veraocode Security Testing tool and i got this Improper Resource Shutdown or Release at the below code:

//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();  
            }   

Someone please help me on this...

Don Roby
  • 40,677
  • 6
  • 91
  • 113
user1782009
  • 299
  • 4
  • 15
  • 32

3 Answers3

2

You need to close your PrintWriter.

f.close();
John Smith
  • 2,282
  • 1
  • 14
  • 22
1
     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();
             }
        }

Resources should be closed in finally clause. So that they definitely get executed. Because if you put closing code in try, and some exception occurs before the closing line. The resource doesn't get closed properly.

Also if you are using JDK-7, have a look at try-with-resources.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
0

You need to close the PrintWriter in catch block also Or create finally block and close the resource.

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

OR

finally {
if (f != null) {
f.close();
}
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Baskar Madasamy
  • 121
  • 1
  • 2
  • 5