'Veracode CWE ID 404 Improper Resource Shutdown or Release
I have this code:
try {
BufferedWriter bw = null;
FileWriter fw = null;
try {
final String fileName = getFileName();
File propertiesFile=new File(getFilesDir(), fileName);
fw = new FileWriter(propertiesFile);
bw = new BufferedWriter(fw);
bw.write(s);
File file = new File(getFilesDir(), fileName);
} catch (IOException e) {
}finally{
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
if(bw != null){
bw.close();
}
}
} catch (Exception e) {
}
Veracode detected a flaw (Improper Resource Shutdown or Release ) on this line bw.write(s); How to fix this? Thanks in advance
Solution 1:[1]
Use try-with-resources starting java 7
try (FileWriter fw = new FileWriter(propertiesFile);
BufferedWriter bw = new BufferedWriter(fw)){
......
}catch (Exception e){}
Solution 2:[2]
Using try finally fix the flaw, and inside finally close the BufferedWriter and the FileWriter
try {
BufferedWriter bw = null;
FileWriter fw = null;
try {
final String fileName = getFileName();
File propertiesFile=new File(getFilesDir(), fileName);
fw = new FileWriter(propertiesFile);
bw = new BufferedWriter(fw);
bw.write(s);
File file = new File(getFilesDir(), fileName);
}finally{
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
}
} catch (Exception e) {
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
