I need to erase a file in my program. My solution was to have an erase() method that would do that like so:
public static void erase(String string) {
FileWriter fw = null;
try {
fw = new FileWriter(string);
fw.write(new String());
} catch (IOException ie) {
e.printStackTrace();
} finally {
fw.flush();
fw.close();
}
}
Several problems here:
-
If the
fwdoes not properly initialize (for whatever reason, missing file, invalid persmissions, etc) then when I try to close it in thefinallyblock, there is a NullPointerException. -
If I don’t have the finally block, then I might be throwing a NullPointerException for the reason above.
-
If I close the file inside the try block, then I might leak the resource if the file properly opens, but doesn’t properly write.
What other problems am I overlooking and how can I harden this method?
You can just wrap the finally functionality in an if-statement:
This will ensure that if the file was ever opened, then it will be closed. If it wasn’t opened in the first place, then it won’t do anything, which is what you want.
Also, I’m not sure if it’s just like that for posting, but it’s generally not advisable to just print a stacktrace in a catch block and continue (“swallowing” the exception). You really should let the exception get thrown because this could hide bugs and make tracking them down very hard.
EDIT: See comment below.